The Python Oracle

Chain-calling parent initialisers in python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 Question
01:25 Accepted answer (Score 170)
01:50 Answer 2 (Score 215)
02:05 Answer 3 (Score 29)
02:29 Thank you

--

Full question
https://stackoverflow.com/questions/9040...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #oop #inheritance #constructor

#avk47



ANSWER 1

Score 218


Python 3 includes an improved super() which allows use like this:

super().__init__(args)



ACCEPTED ANSWER

Score 170


The way you are doing it is indeed the recommended one (for Python 2.x).

The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".




ANSWER 3

Score 29


You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"