python call super constructor


If you want to call the constructor of a parent class you have a couple of options. For example:

class Parent(object):
  def __init__(self):
    print 'called Parent Constructor'

class Child(Parent):
  def __init__(self):
    print 'called Child Constructor'
    super(Child,self).__init__()

In this first example we are talking about “new-style” classes. Basically these are classes that inherit from “object” ( class Parent(object) ). In this case you can call the super() method with a reference to Child and self ( super(Child,self).__init__() ).

python call constructor of parent class

In python you can also use “old-style” classes (they do not inherit from “object”):

 

class Parent:
  def __init__(self):
    print 'called Parent Constructor'

class Child(Parent):
  def __init__(self):
    print 'called Child Constructor'
    Child.__init__(self)

 

In this case you just call “Child.__init__(self)” directly.

If you want to learn more about Python please check out this article: best way to learn python.