我正在用python学习OOPs。创建下面的代码来复制多重继承中的菱形问题。我在jupyter笔记本中运行下面的代码,同时生成输出。你知道吗
class parent:
def __init__(self):
self.a=2
self.b=4
def form1(self):
print("calling parent from1")
print('p',self.a+self.b)
class child1(parent):
def __init__(self):
self.a=50
self.b=4
def form1(self):
print('bye',self.a-self.b)
def callchildform1(self):
print("calling parent from child1")
super().form1()
class child2(parent):
def __init__(self):
self.a=3
self.b=4
def form1(self):
print('hi',self.a*self.b)
def callchildform1(self):
print("calling parent from child2")
super().form1()
class grandchild(child1,child2):
def __init__(self):
self.a=10
self.b=4
def callingparent(self):
super().form1()
g=grandchild()
g.form1()
g.callchildform1()
g.callingparent()
输出低于
bye 6
calling parent from child1
hi 40
bye 6
我可以理解“再见6”输出的时间,但它是如何打印“高40”。我是新来的,所以任何人都可以解释这里发生了什么。你知道吗
您可以找到类的
__mro__
属性。这里,MRO代表MethodResolutionOorder。你知道吗考虑一下对代码的这种修改:
输出为:
运行
g.callchildform1()
时,Python会在Grandchild
中查找callchildform1
的定义。它不在那里,所以下一个看起来的地方是Child1
。从示例和方法解析顺序可以看出,当Grandchild
的实例调用Child1
中定义的方法(该方法调用super()
)时,对被调用方法的搜索将从Child2
开始。你知道吗相关问题 更多 >
编程相关推荐