【问题标题】:super() usage in multiple inheritance in pythonpython中多重继承中的super()用法
【发布时间】:2017-05-13 16:58:04
【问题描述】:

我是 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'

【问题讨论】:

    标签: python python-3.x super


    【解决方案1】:

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

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

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

    所以从D开始,下一个类是B,然后是Cobject。从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
    

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 2020-11-27
      • 1970-01-01
      • 2020-07-05
      • 2015-12-24
      • 1970-01-01
      相关资源
      最近更新 更多