class – How to invoke the super constructor in Python?

class – How to invoke the super constructor in Python?

In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:

Python-3.x

class A(object):
 def __init__(self):
   print(world)

class B(A):
 def __init__(self):
   print(hello)
   super().__init__()

Python-2.x

In python 2.x, you have to call the slightly more verbose version super(<containing classname>, self), which is equivalent to super()as per the docs.

class A(object):
 def __init__(self):
   print world

class B(A):
 def __init__(self):
   print hello
   super(B, self).__init__()

super() returns a parent-like object in new-style classes:

class A(object):
    def __init__(self):
        print(world)

class B(A):
    def __init__(self):
        print(hello)
        super(B, self).__init__()

B()

class – How to invoke the super constructor in Python?

With Python 2.x old-style classes it would be this:

class A: 
 def __init__(self): 
   print world 

class B(A): 
 def __init__(self): 
   print hello 
   A.__init__(self)

Leave a Reply

Your email address will not be published.