In Python, how do I pick which Parent's method to call? Say I want to call the parent ASDF2's __init__
method. Seems like I have to specify ASDF1 in the super()..? And if I want to call ASDF3's __init__
, then I must specify ASDF2?!
>>> class ASDF(ASDF1, ASDF2, ASDF3): def __init__(self): super(ASDF1, self).__init__() >>> ASDF() ASDF2's __init__ happened >>> class ASDF(ASDF1, ASDF2, ASDF3): def __init__(self): super(ASDF2, self).__init__() >>> ASDF() ASDF3's __init__ happened
Seems bonkers to me. What am I doing wrong?
How does Python's super() work with multiple inheritance? Before going to explain super() first we need to know about multiple inheritance concept. Multiple inheritance : Means one child class can inherit multiple parent classes. In the following example Child class inherited attributes methods from the Parent class.
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 is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
If there are superclass [init] you want to call, you have to explicitly call them with super(). __init__() recursively. If there is no [init] defined along the tree path, nothing will be called. It is just an ordinary function that is automatically called once at construction time.
That's not what super()
is for. Super basically picks one (or all) of its parents in a specific order. If you only want to call a single parent's method, do this
class ASDF(ASDF1, ASDF2, ASDF3): def __init__(self): ASDF2.__init__(self)
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