Subclasses and Constructor Inheritance in Python
Posted:
Thursday, September 13th, 2012Last modified:
Friday, May 1st, 2015Topics:
PythonNotes on subclasses and constructor inheritance in Python.
__metaclass__ = type class A(): def __init__(self): self.foo = True def bar(self): if self.foo: print 'Foo is TRUE!' else: print 'Foo is NOT true.' a = A() a.bar() # Prints "Foo is TRUE!" class B(A): 'Subclass of A without inherited constructor.' def __init__(self): self.color = 'Red' def printColor(self): print self.color b = B() b.printColor() # Prints "Red" #b.bar() # Throws and error because self.foo doesn't exist in class B! class C(A): 'Subclass of A with constructor inherited the older way.' def __init__(self): self.fruit = 'Banana!' #A.__init__(self) # This is the old way of inheriting a superclass constructor. super(C, self).__init__() # This is the new way of inheriting a superclass constructor. # Note that super() needs to get the superclass of C(). def printFruit(self): print self.fruit c = C() c.printFruit() # Prints "Banana!" c.bar() # Prints "Foo is TRUE!"
Available Wiki Topics
The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.