多重继承:派生类仅从一个基类获取属性?
我试图学习Python中的多重继承的概念.考虑从两个类Base1
和Base2
派生的类Derv
. Derv
仅继承第一个基类的成员:
I was trying to learn the concepts of multiple-inheritance in Python. Consider a class Derv
derived from two classes, Base1
and Base2
. Derv
inherits members from the first base class only:
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 }
.
The result is { 'x' : 10 }
and reversing the order of inheritance gives only { 'y' : 10 }
.
派生类是否应该继承两个基类的属性?
Shouldn't the derived class inherit attributes from both the base classes?
我不完全理解为什么会这样,但是我可以告诉您如何解决它:
I don't fully understand why it's like this, but I can tell you how to fix it:
由于某种原因,Python仅调用其父级之一的__init__
方法.但是,这可以解决您的问题:
For some reason, Python only calls the __init__
method of one of it's parents. However, this fixes your problem:
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}
更新,添加打印语句实际上可以说明情况.例如
Update, adding print statements actually sheds some light on the situation. For example,
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}