Skip to content

Instantly share code, notes, and snippets.

@gokul-uf
Last active December 28, 2015 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gokul-uf/349ffff735568213516f to your computer and use it in GitHub Desktop.
Save gokul-uf/349ffff735568213516f to your computer and use it in GitHub Desktop.
OOP in Python: Gist for my blogpost at gokul-uf.github.io
'''References:
1. https://developer.mozilla.org/en-US/Learn/Python/Quickly_Learn_Object_Oriented_Programming#start
2. http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods
3. http://www.artima.com/weblogs/viewpost.jsp?thread=236275
4. https://docs.python.org/2/glossary.html#term-new-style-class
'''
class A:
#public attributes
intAttribute = 0
charAttribute = 'a'
__hiddenAttribute = 'shh!'
#Python does not have private attributes, it makes do with name-mangling which automatically prefixs the
#Class Name to variable names which start with __ (double underscore.
#To access it, use
#instanceName._className__attrName
#This is called name-mangling
#REF: https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references
#public method, dummy getters and setters
#NOTE self is a variable which refers to the current object; needed for context
def getIntAttribute(self):
return self.intAttribute
def setIntAttribute(self,value):
if type(value) is int:
self.intAttribute = value
else:
raise TypeError
def __init__(self): #Constructor
intAttribute = -1
charAttrribute = 'b'
def __del__(self): #Destructor
print "hope you learnt something, bye"
del self
class B:
#dummy class, nothing big here
intAttribute = 1
#Inherited class. Python allows multiple inheritance
class C (A,B):
intAttribute = 2
def printIntAttribute(self):
print "A's intAttribute value {}".format(A.intAttribute) #accessing hidden attributes
print "B's intAttribute value {}".format(B.intAttribute)
print "C's intAttribute value {}".format(self.intAttribute)
if __name__ == '__main__':
a = A()
print "A's intAttribute: {}".format(a.intAttribute)
print "A's charAttribute: {}".format(a.charAttribute)
print "using the getter to access integer, it is: {}".format(a.getIntAttribute())
a.setIntAttribute(6)
print "Accessing the hidden attribute: "+a._A__hiddenAttribute
'''
NOTE
a.setIntAttribute(a,5) Won't work
Will say
File "oop.py", line 24, in <module>
a.setIntAttribute(a,5)
TypeError: setIntAttribute() takes exactly 2 arguments (3 given)
The self argument is sent implicitly and needn't be mentioned
'''
print "After changing the value: {}".format(a.getIntAttribute())
c = C()
c.printIntAttribute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment