【发布时间】:2018-08-28 12:50:52
【问题描述】:
[使用Python3.6] 我有一个设计,其中孙子继承了(父母的)父母和孩子。
class Parent:
def aux_func(self):
return "[parent aux]"
def main_func(self):
print("[parent main]" + self.aux_func())
class Child(Parent):
def aux_func(self):
return "[child aux]"
def main_func(self):
print("[child main]" + self.aux_func())
class Grandchild(Child, Parent):
@classmethod
def do_something(cls):
g = Grandchild()
g.main_func()
super(Child, g).main_func()
Parent.main_func(g)
Grandchild.do_something()
结果是 -
[child main][child aux]
[parent main][child aux]
[parent main][child aux]
从 Parent 调用函数会导致 aux_func 从 Child 类解析。我试图通过 MRO 流程,但无法解释从不同类调用的函数。有人可以帮我吗
- 为什么会这样?
- 实现 [parent main][parent aux] 的解决方法是什么?
【问题讨论】:
-
您将错误的课程传递给
super()。传入 current 类,Grandchild. -
@MartijnPieters - 感谢您的参与。问题是
super(Grandchild, g).main_func()给了我[child main][child aux]。我正在尝试调用两个父函数。 -
好吧,
self仍然是Grandchild()类的一个实例。super()不会改变self的绑定对象。 -
@MartijnPieters - 这可以解释。谢谢!我正在尝试提出一种设计,允许我从父或子调用所有函数,但不能同时调用两者。有什么建议吗?
标签: python python-3.6 multiple-inheritance method-resolution-order