This is detailed with a reasonable amount of detail by Guido himself in his blog post Method Resolution Order (including two earlier attempts).
In your example, Third() will call First.__init__. Python looks for each attribute in the class's parents as they are listed left to right. In this case, we are looking for __init__. So, if you define
class Third(First, Second):
...
Python will start by looking at First, and, if First doesn't have the attribute, then it will look at Second.
This situation becomes more complex when inheritance starts crossing paths (for example if First inherited from Second). Read the link above for more details, but, in a nutshell, Python will try to maintain the order in which each class appears on the inheritance list, starting with the child class itself.
So, for instance, if you had:
class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First):
def __init__(self):
print "third"
class Fourth(Second, Third):
def __init__(self):
super(Fourth, self).__init__()
print "that's it"
the MRO would be [Fourth, Second, Third, First].
By the way: if Python cannot find a coherent method resolution order, it'll raise an exception, instead of falling back to behavior which might surprise the user.
Example of an ambiguous MRO:
class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
print "third"
Should Third's MRO be [First, Second] or [Second, First]? There's no obvious expectation, and Python will raise an error:
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution order (MRO) for bases Second, First
Why do the examples above lack super() calls? The point of the examples is to show how the MRO is constructed. They are not intended to print "first\nsecond\third" or whatever. You can – and should, of course, play around with the example, add super() calls, see what happens, and gain a deeper understanding of Python's inheritance model. But my goal here is to keep it simple and show how the MRO is built. And it is built as I explained:
>>> Fourth.__mro__
(<class '__main__.Fourth'>,
<class '__main__.Second'>, <class '__main__.Third'>,
<class '__main__.First'>,
<type 'object'>)
Answer from rbp on Stack OverflowThis is detailed with a reasonable amount of detail by Guido himself in his blog post Method Resolution Order (including two earlier attempts).
In your example, Third() will call First.__init__. Python looks for each attribute in the class's parents as they are listed left to right. In this case, we are looking for __init__. So, if you define
class Third(First, Second):
...
Python will start by looking at First, and, if First doesn't have the attribute, then it will look at Second.
This situation becomes more complex when inheritance starts crossing paths (for example if First inherited from Second). Read the link above for more details, but, in a nutshell, Python will try to maintain the order in which each class appears on the inheritance list, starting with the child class itself.
So, for instance, if you had:
class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First):
def __init__(self):
print "third"
class Fourth(Second, Third):
def __init__(self):
super(Fourth, self).__init__()
print "that's it"
the MRO would be [Fourth, Second, Third, First].
By the way: if Python cannot find a coherent method resolution order, it'll raise an exception, instead of falling back to behavior which might surprise the user.
Example of an ambiguous MRO:
class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
print "third"
Should Third's MRO be [First, Second] or [Second, First]? There's no obvious expectation, and Python will raise an error:
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution order (MRO) for bases Second, First
Why do the examples above lack super() calls? The point of the examples is to show how the MRO is constructed. They are not intended to print "first\nsecond\third" or whatever. You can – and should, of course, play around with the example, add super() calls, see what happens, and gain a deeper understanding of Python's inheritance model. But my goal here is to keep it simple and show how the MRO is built. And it is built as I explained:
>>> Fourth.__mro__
(<class '__main__.Fourth'>,
<class '__main__.Second'>, <class '__main__.Third'>,
<class '__main__.First'>,
<type 'object'>)
Your code, and the other answers, are all buggy. They are missing the super() calls in the first two classes that are required for co-operative subclassing to work. Better is:
class First(object):
def __init__(self):
super(First, self).__init__()
print("first")
class Second(object):
def __init__(self):
super(Second, self).__init__()
print("second")
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print("third")
Output:
>>> Third()
second
first
third
The super() call finds the next method in the MRO at each step, which is why First and Second have to have it too, otherwise execution stops at the end of Second.__init__().
Without the super() calls in First and Second, the output is missing second:
>>> Third()
first
third
A question about super() and multiple inheritance...
Multiple Inheritance weirdness
Multiple inheritance with ABC: which order?
Multiple Inheritance, super(), and different parameters
Videos
If I run the following code I get an error.
class A:
"""
This is the object which the other two objects
will inherit from.
"""
def __init__(self, a): print(a)
class B(A):
"""
This is one of the parent objects.
"""
def __init__(self, a, b):
super().__init__(a)
print(b)
class C(A):
"""
And the other one...
"""
def __init__(self, a, c):
super().__init__(a)
print(c)
class D(B, C):
"""
And here's the problem:
"""
def __init__(self, a, b, c, d):
B.__init__(self, a, b)
C.__init__(self, a, c)
print(d)
D('a', 'b', 'c', 'd')The problem with this code is that I have an object which inherits from two different objects that both use the super() method in their constructors. From the object D, I'm calling the constructors of the objects B and C. The problem is that I'm calling them using the parent classes' identifiers and passing the child object as the self argument. When the class B calls super().__init__, the interpreter understands that it's being called from the object D. The interpreter does its best and calls the constructor for C, but the constructor of B is calling the constructor of C via super() only with the parameter a, so a positional argument gets missing and I get this error:
Traceback (most recent call last):
File ".../test.py", line 39, in <module>
D('a', 'b', 'c', 'd')
File ".../test.py", line 33, in __init__
B.__init__(self, a, b)
File ".../test.py", line 15, in __init__
super().__init__(a)
TypeError: __init__() missing 1 required positional argument: 'c'Does anyone know if I can choose which constructor to call using the super() function? Or if anyone has another better idea, I'd be thankful (because my code is quite a mess...).
Hi,
I'm working on a class which needs to inherit from two different classes. I can find lots of articles online about multiple inheritance, however _none_ of them details what to do if the inherited classes both have different parameters. Take, for example:
class A:
def __init__(self,foo):
self.foo = foo
class B:
def __init__(self,bar):
self.bar = bar
class AB(A,B):
def __init__(self,foo,bar):
super().__init__(foo=foo,bar=bar)
AB("f","b")This fails because super()._init__() only expected foo. How can I work super() work with multiple inheritance where the parameters are different??