【问题标题】:How to use `super` in multiple inheritance?如何在多重继承中使用`super`?
【发布时间】:2020-03-20 20:29:56
【问题描述】:

假设我们定义了两个类:

class A():
    def __init__(self):
        self.a = 0

class B():
    def __init__(self):
        self.b = 0

现在,我们要定义第三个类C,它继承自AB

class C(A, B):
    def __init__(self):
        A.__init__(self)   # how to do this using super()
        B.__init__(self)   # how to do this using super()

【问题讨论】:

标签: python python-3.x multiple-inheritance super


【解决方案1】:

您没有指定您是 Python 2 还是 Python 3,这很重要,我们将看到。但无论哪种方式,如果您将在派生类中使用super() 来初始化基类,那么基类也必须使用super()。所以,

对于 Python 3:

class A():
    def __init__(self):
        super().__init__()
        self.a = 0

class B():
    def __init__(self):
        super().__init__()
        self.b = 0

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

对于 Python 2(类必须是新式类)或 Python 3

class A(object):
    def __init__(self):
        super(A, self).__init__()
        self.a = 0

class B(object):
    def __init__(self):
        super(B, self).__init__()
        self.b = 0

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

【讨论】:

  • 我用的是 Python 3。但是我不明白为什么在基类中添加 super() 可以解决问题?
  • @ThunderPheonix 您应该阅读 Daniel Roseman 发布到您原始帖子的评论和链接,即 Deep Thoughts by Raymond Hettinger,尤其是 Python 的 super() 被认为是超级的部分!实用建议小节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 2017-07-30
  • 2022-01-20
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
相关资源
最近更新 更多