This code shows error: AttributeError: 'super' object has no attribute 'method'
this same code does not shows error when "super.method()" is removed in class C. Why?
class A(object):
def method(self):
print("\n class A method")
super().method()
class B(object):
def method(self):
print("\n class B method")
super().method()
class C(object):
def method(self):
print("\n class C method")
super().method()
class X(A, B):
def method(self):
print("\n class X method")
super().method()
class Y(B, C):
def method(self):
print("\n class Y method")
super().method()
class P(X, Y, C):
def method(self):
print("\n class P method")
super().method()
p = P()
p.method()
print(P.mro())
I want to know, why this program is showing errors when "super().method" is included in class C, and why this same program is NOT SHOWING ERROR, when "super().method" is removed in class C?
This is not a bug, but a feature of working with multiple inheritance and
super. Let me answer your questions one by one:The reason is that the base class
objectdoes not have a method calledmethod. You will see the same exception when callingC().method()or simplyobject().method(). So I guess this is quite expected.This is the magic of python's method resolution order (MRO). If you execute
you should see
Here, you see that a
supercall will not call all parents of a class until the top of the inheritance tree and then take the next class. Instead, it will call them according to their "generation".Look at the following example:
Which will give you
You do not see the line
Base, becausesuperinParentAis ignored due to the presence ofParentBwhich shares the same base.However, if you swap the inheritance, you will see the line
Baseprinted. In short, follow the MRO, but if the last class in a generation does not call super, the chain stops.I agree that this is not intuitive, but in practice this is rarely a problem, or if you have to think about the MRO to understand the code, it would be a good candidate for refactoring.
To understand the MRO, I recommend to read https://en.wikipedia.org/wiki/C3_linearization or other related questions at SO.