Python Call Parent Method Multiple Inheritance
所以,我遇到了这样的情况。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class A(object): def foo(self, call_from): print"foo from A, call from %s" % call_from class B(object): def foo(self, call_from): print"foo from B, call from %s" % call_from class C(object): def foo(self, call_from): print"foo from C, call from %s" % call_from class D(A, B, C): def foo(self): print"foo from D" super(D, self).foo("D") d = D() d.foo() |
代码的结果是
1 2 | foo from D foo from A, call from D |
号
我想从
在除
1 2 | >>> D.__mro__ (<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <type 'object'>) |
你不需要在
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class A(object): def foo(self, call_from): print"foo from A, call from %s" % call_from super(A,self).foo('A') class B(object): def foo(self, call_from): print"foo from B, call from %s" % call_from super(B, self).foo('B') class C(object): def foo(self, call_from): print"foo from C, call from %s" % call_from class D(A, B, C): def foo(self): print"foo from D" super(D, self).foo("D") d = D() d.foo() |
号
输出:
1 2 3 4 | foo from D foo from A, call from D foo from B, call from A foo from C, call from B |
你可以这样使用
1 2 3 4 5 | class D(A, B, C): def foo(self): print"foo from D" for cls in D.__bases__: cls().foo("D") |
。
随着这一变化,输出将
1 2 3 4 | foo from D foo from A, call from D foo from B, call from D foo from C, call from D |
我认为,在子类中调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class A: def foo(self, call_from): print(f"foo from A, call from {call_from}") super().foo('A') class B: def foo(self, call_from): print(f"foo from B, call from {call_from}") super().foo('B') class C(object): def foo(self, call_from): print(f"foo from C, call from {call_from}") super().foo('C') class StopFoo: def foo(self, call_from): pass class D(A, B, C, StopFoo): def foo(self, call_from): print(f"foo from D, call from {call_from}") super().foo('D') |
。
如果运行此代码:
1 2 | d = D() d.foo('D') |
。
你会得到:
1 2 3 4 | foo from D, call from D foo from A, call from D foo from B, call from A foo from C, call from B |
这种策略的优点是,只要包含
对于带有钩子的混合模式,这可能是有意义的。但是,当然,解决方案在每种情况下也没有那么有用。不要害怕