Skip to main content
 首页 » 编程设计

python之python 多重继承中的 super() 用法

2025年05月04日17telwanggs

我是 python 新手。我试图了解 python 多重继承中的 super() 功能。

class B(): 
    def __init__(self): 
        print("__init__ of B called") 
        self.b = "B" 
 
class C(): 
    def __init__(self): 
        print("__init__ of C called") 
        self.c = "C" 
 
class D(B, C): 
    def __init__(self): 
        print("__init__ of D called") 
        super().__init__() 
 
    def output(self): 
        print(self.b, self.c) 
 
d = D() 
d.output() 

我收到以下错误:

AttributeError: 'D' object has no attribute 'c' 

请您参考如下方法:

super() 将在 MRO 序列中找到下一个方法。这意味着您的基类中只有 一个 __init__ 方法会被调用。

您可以通过查看 __mro__ attribute 来检查 MRO(方法解析顺序)类的:

>>> D.__mro__ 
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>) 

所以从 D 开始,下一个类是 B,接着是 C 和 object。从 D.__init__() 开始,super().__init__() 表达式只会调用 B.__init__(),然后因为 C.__init__() 从未调用,self.c 也未设置。

您必须向您的类实现添加更多 super() 调用;不带参数调用 object.__init__() 是安全的,因此只需在此处处使用它们:

class B(): 
    def __init__(self): 
        print("__init__ of B called") 
        super().__init__() 
        self.b = "B" 
 
class C(): 
    def __init__(self): 
        print("__init__ of C called") 
        super().__init__() 
        self.c = "C" 
 
class D(B, C): 
    def __init__(self): 
        print("__init__ of D called") 
        super().__init__() 
 
    def output(self): 
        print(self.b, self.c) 

现在 B.__init__ 将调用 C.__init__,而 C.__init__ 将调用 object.__init__ ,并调用 D().output() 有效:

>>> d = D() 
__init__ of D called 
__init__ of B called 
__init__ of C called 
>>> d.output() 
B C