Consider the following snippet of python code
class A(object): def __init__(self, a): self.a = a class B(A): def __init__(self, a, b): super(B, self).__init__(a) self.b = b class C(A): def __init__(self, a, c): super(C, self).__init__(a) self.c = c class D(B, C): def __init__(self, a, b, c, d): #super(D,self).__init__(a, b, c) ??? self.d = d
I am wondering how can I pass a
, b
and c
to corresponding base classes' constructors.
In fact, multiple inheritance is the only case where super() is of any use. I would not recommend using it with classes using linear inheritance, where it's just useless overhead.
Understanding Python super() with __init__() methods It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. The super() function allows us to avoid using the base class name explicitly.
The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.
In a class hierarchy with single inheritance, super helps to refer to the parent classes without naming them explicitly, thus making the code more maintainable. Here, with the help of super(). f1(), the f1() method of the super class of Child class i.e Parent class has been called without explicitly naming it.
Well, when dealing with multiple inheritance in general, your base classes (unfortunately) should be designed for multiple inheritance. Classes B
and C
in your example aren't, and thus you couldn't find a proper way to apply super
in D
.
One of the common ways of designing your base classes for multiple inheritance, is for the middle-level base classes to accept extra args in their __init__
method, which they are not intending to use, and pass them along to their super
call.
Here's one way to do it in python:
class A(object): def __init__(self,a): self.a=a class B(A): def __init__(self,b,**kw): self.b=b super(B,self).__init__(**kw) class C(A): def __init__(self,c,**kw): self.c=c super(C,self).__init__(**kw) class D(B,C): def __init__(self,a,b,c,d): super(D,self).__init__(a=a,b=b,c=c) self.d=d
This can be viewed as disappointing, but that's just the way it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With