Subclasses and Constructor Inheritance in Python

Last modified: 
Friday, May 1st, 2015

Notes on subclasses and constructor inheritance in Python.

__metaclass__ = type

class A():
  def __init__(self): = True
  def bar(self):
      print 'Foo is TRUE!'
      print 'Foo is NOT true.'

a = A() # 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" # Throws and error because 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!" # Prints "Foo is TRUE!"

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.