In Python 2.7 and 3, I use the following method to call a super-class's function:
class C(B):
def __init__(self):
B.__init__(self)
I see it's also possible to replace B.__init__(self)
with super(B, self).__init__()
and in python3 super().__init__()
.
Are there any advantages or disadvantages to doing this either way? It makes more sense to call it from B
directly for me at least, but maybe there's a good reason where super()
can only be used when using metaclasses (which I generally avoid).
For single inheritance,
super()
is just a fancier way to refer to the base type. That way, you make the code more maintainable, for example in case you want to change the base type’s name. When you are usingsuper
everywhere, you just need to change it in theclass
line.The real benefit comes with multiple inheritance though. When using
super
, a single call will not only automatically call the method of all base types (in the correct inheritance order), but it will also make sure that each method is only called once.This essentially allows types to have a diamond property, e.g. you have a single base type
A
, and two typesB
andC
which both derive fromA
. And then you have a typeD
which inherits from bothB
andC
(making it implicitely inherit fromA
too—twice). If you call the base types’ methods explicitely now, you will end up calling A’s method twice. But usingsuper
, it will only call it once:When we now instantiate
D
, we get the following output:Now, let’s do all that again with manually calling the base type’s method:
And this is the output:
As you can see,
A2
occurs twice. This is usually not what you want. It gets even messier when you manually call method of one of your base types that usessuper
. So instead, you should just usesuper()
to make sure everything works, and also so you don’t have to worry about it too much.