请帮我理解Python中多重继承的概念(我来自C#背景,不支持多重继承)。
我使用的是Python 3.7.6。
在下面的代码中,类 Apple
继承了类 ToyFruit
、NaturalFruit
、FakeFruit
和 >机器人水果
。虽然 ToyFruit
、NaturalFruit
和 FakeFruit
继承 Fruit
基类,但 RoboticFruit
有一个不同的BaseClass
Robot
。
我注意到 RoboticFruit
和 Robot
根本没有被调用。
class Fruit:
def __init__(self, name):
print("This is the Fruit __init__ function")
self.test = "BaseClass"
self.name = name
print("Fruit object created")
class NaturalFruit(Fruit):
def __init__(self, name):
print("This is the NaturalFruit __init__ function")
super().__init__(name)
self.type = "Natural"
print("This is a Natural Fruit")
self.test = "NaturalClass"
print("Natural Fruit object created")
class FakeFruit(Fruit):
def __init__(self, name):
print("This is the FakeFruit __init__ function")
super().__init__(name)
self.type = "Fake"
print("This is a Fake Fruit")
self.test = "FakeClass"
print("Fake Fruit object created")
class ToyFruit(Fruit):
def __init__(self, name):
print("This is the ToyFruit __init__ function")
super().__init__(name)
self.type = "Toy"
print("This is the Toy Fruit")
self.test = "ToyClass"
print("Toy Fruit object created")
class Robot:
def __init__(self, name):
print("This is the ROBOT __init__ function")
self.test = "RobotClass"
self.name = name
print("Robot object created")
class RoboticFruit(Robot):
def __init__(self, name):
super().__init__("RoboticFruit")
print("Robotic Fruit")
class Apple(ToyFruit, NaturalFruit, FakeFruit, RoboticFruit):
def __init__(self):
super().__init__("Apple")
print("Apple object created")
apple = Apple()
# print(apple.name)
print(apple.test)
输出:-
This is the ToyFruit __init__ function
This is the NaturalFruit __init__ function
This is the FakeFruit __init__ function
This is the Fruit __init__ function
Fruit object created
This is a Fake Fruit
Fake Fruit object created
This is a Natural Fruit
Natural Fruit object created
This is the Toy Fruit
Toy Fruit object created
Apple object created
ToyClass
如果我将订单交换为
class Apple(RoboticFruit, ToyFruit, NaturalFruit, FakeFruit):
然后,ToyFruit
、NaturalFruit
、FakeFruit
和 Fruit
__init__
方法是根本没有被调用。
我不明白为什么 RoboticFruit
类构造函数被跳过。
最佳答案
在多重继承的情况下,super()
委托(delegate)给方法解析顺序 (MRO) 中的下一个对象。我们可以看到Apple类的MRO:
print(Apple.__mro__)
# output:
(
<class '__main__.Apple'>,
<class '__main__.ToyFruit'>,
<class '__main__.NaturalFruit'>,
<class '__main__.FakeFruit'>,
<class '__main__.Fruit'>,
<class '__main__.RoboticFruit'>,
<class '__main__.Robot'>,
<class 'object'>
)
所以我认为 RoboticFruit
和 Robot
没有被调用,因为类中没有像 super().__init__(name)
这样的调用Fruit
,这是该顺序中 RoboticFruit
的前一个 (MRO)。如果您在 Fruit
中添加对 super()
的调用,它应该可以正常工作:
class Fruit:
def __init__(self, name):
print("This is the Fruit __init__ function")
super().__init__(name)
self.test = "BaseClass"
self.name = name
print("Fruit object created")
关于python - 具有多个基类的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59907412/