首页 > 解决方案 > 访问在多重继承中被覆盖的第二个父方法

问题描述

“我无法使用超级方法访问第二个父类的方法,但是当我在超级中使用产品时,它会显示电话类中方法的结果”

class Phone:

    def __init__(self, price, brand, camera):
        print ("Inside phone constructor")
        self.__price = price
        self.brand = brand
        self.camera = camera

    def buy(self):
        print ("Buying a phone")

    def return_phone(self):
        print ("Returning a phone")

class Product:

    def buy(self):
        print ("Product buy method")


class SmartPhone(Product, Phone):

    def call(self):
        super(Phone,self).buy()



s=SmartPhone(20000, "Apple", 12)
s.call()

“我期待 Phone 类的输出,而不是我收到错误”

Inside phone constructor

Runtime Exception
Traceback (most recent call last):
File "file.py", line 26, in <module>
s.call()
File "file.py", line 22, in call
super(Phone,self).buy()
AttributeError: 'super' object has no attribute 'buy'

标签: python-3.x

解决方案


多重继承:

class SmartPhone(Product, Phone):
    def call(self):
        Phone.buy(self)
        Product.buy(self)

输出:

Inside phone constructor
Buying a phone
Product buy method

注意:如果我理解你想要什么。您试图将该功能用于错误的目的

下面是一个继承自三个超类的类的示例:

class D(C, B, A):
    def __init__(self):
       super().__init__()

由于您调用了 super() 对象,这与调用所有三个超类方法__init__基本相同:__init__

class D(C, B, A):
    def __init__(self):
       C.__init__()
       B.__init__()
       A.__init__()

推荐阅读