How to invoke the super constructor in Python?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization
--
Chapters
00:00 Question
00:28 Accepted answer (Score 424)
01:14 Answer 2 (Score 378)
01:31 Answer 3 (Score 53)
01:47 Answer 4 (Score 37)
02:54 Thank you
--
Full question
https://stackoverflow.com/questions/2399...
Accepted answer links:
[the docs]: https://docs.python.org/3.5/library/func...
Answer 4 links:
[here]: http://fuhm.net/super-harmful/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #class #inheritance #constructor #superclass
#avk47
ACCEPTED ANSWER
Score 462
In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python 3 the process has been simplified:
Python 3
class A(object):
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
super().__init__()
Python 2
In Python 2, 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__()
ANSWER 2
Score 377
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()
ANSWER 3
Score 54
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)
ANSWER 4
Score 37
One way is to call A's constructor and pass self as an argument, like so:
class B(A):
def __init__(self):
A.__init__(self)
print "hello"
The advantage of this style is that it's very clear. It call A's initialiser. The downside is that it doesn't handle diamond-shaped inheritance very well, since you may end up calling the shared base class's initialiser twice.
Another way is to use super(), as others have shown. For single-inheritance, it does basically the same thing as letting you call the parent's initialiser.
However, super() is quite a bit more complicated under-the-hood and can sometimes be counter-intuitive in multiple inheritance situations. On the plus side, super() can be used to handle diamond-shaped inheritance. If you want to know the nitty-gritty of what super() does, the best explanation I've found for how super() works is here (though I'm not necessarily endorsing that article's opinions).