super confusing python multiple inheritance super()

 ̄綄美尐妖づ 提交于 2019-11-30 13:05:32

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!