The Python Oracle

Chain-calling parent initialisers in python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 Chain-Calling Parent Initialisers In Python
01:01 Accepted Answer Score 170
01:23 Answer 2 Score 218
01:34 Answer 3 Score 29
01:49 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"