Super Confusing Python Multiple Inheritance Super()
I was playing around with the multiple inheritance in python and I come a cross a situation that I can't understand how it happen. Here is the inheritance layout: A F /
Solution 1:
The whole point of super()
is to follow the method resolution order. That's why you tell it your own class, not your parent class. It's hard for the programmer to predict which class will be invoked next, so you let super()
take care of it.
You already had B called from D, so how could you then get C called from D? D.foo() can only call one other foo(), because you only have one function call there. It's going to be a linear chain of calls, so the classes have to be linearized, that's what the method resolution order does.
Solution 2:
Occasionally I find it useful to call super on parent class. Ex.
class TmpClass0(object):
def tmp_method(self):
print 'TmpClass0 tmp_method'
class TmpClass1(TmpClass0):
def tmp_method(self):
print 'TmpClass1 tmp_method'
Now I want to use TmpClass0's tmp_method from an instance of TmpClass2.
class TmpClass2(TmpClass1):
def tmp_method(self):
super(TmpClass1, self).tmp_method()
Result:
In [107]: tmp_class2 = TmpClass2()
In [108]: tmp_class2.tmp_method()
TmpClass0 tmp_method
Post a Comment for "Super Confusing Python Multiple Inheritance Super()"