我试图学习Python中多重继承的概念。考虑一个类Derv
派生自两个类,Base1
and Base2
. Derv
仅继承第一个基类的成员:
class Base1:
def __init__(self):
self.x=10
class Base2:
def __init__(self):
self.y=10
class Derv (Base1, Base2):
pass
d = Derv()
print (d.__dict__)
结果是{ 'x' : 10 }
并颠倒继承顺序仅给出{ 'y' : 10 }
.
派生类不应该继承两个基类的属性吗?
我不完全明白为什么会这样,但我可以告诉你如何解决它:
由于某种原因,Python 只调用__init__
它的父母之一的方法。但是,这可以解决您的问题:
class Base1:
def __init__(self):
super().__init__()
print('b1')
self.x=10
class Base2:
def __init__(self):
super().__init__() # This line isn't needed. Still not sure why
print('b2')
self.y=10
class Derv (Base1, Base2):
def __init__(self):
super().__init__()
d = Derv()
print (d.__dict__)
'b2'
'b1'
{'y': 10, 'x': 10}
更新,添加打印语句实际上可以说明情况。例如,
class Base1:
def __init__(self):
print('Before Base1 call to super()')
super().__init__()
print('b1')
self.x=10
class Base2:
def __init__(self):
print('Before Base2 call to super()')
super().__init__() # No remaining super classes to call
print('b2')
self.y=10
class Derv (Base1, Base2):
def __init__(self):
super().__init__()
d = Derv()
print (d.__dict__)
'Before Base1 call to super()' # Just before the call to super
'Before Base2 call to super()' # Just before call to super (but there are no more super classes)
'b2' # Calls the remaining super's __init__
'b1' # Finishes Base1 __init__
{'y': 10, 'x': 10}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)