Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's Multiple Inheritance: Picking which super() to call

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?

like image 216
Name McChange Avatar asked Jan 07 '13 23:01

Name McChange


People also ask

How super works in multiple inheritance in Python?

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.

What does super () __ Init__ do?

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.

What is the main purpose of super () method in inheritance?

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.

Does Python automatically call super?

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.


1 Answers

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) 
like image 126
Falmarri Avatar answered Sep 20 '22 17:09

Falmarri