【问题标题】:Python Multiple Inheritance child(parent1, parent2) access parent2 __init__Python 多重继承 child(parent1, parent2) 访问 parent2 __init__
【发布时间】:2022-01-21 18:23:04
【问题描述】:

假设我有这门课

class child(parent1, parent2):
    pass

如果 parent1 也有一个定义的__init__,是否可以访问parent2.__init__?。

这是我的完整代码。

class parent1:
    def __init__(self):
        self.color="Blue"

class parent2:
    def __init__(self):
        self.figure="Triangle"

class child(parent1,parent2):
    pass


juan=child()
try:
    print(juan.color)
except Exception as e:
    print(e)
try:
    print(juan.figure)
except Exception as e:
    print(e)

print(juan.__dict__)

我试过了

class child(parent1,parent2):
    def __init__(self):
        super(parent2).__init__()

但也许我错过了什么?

谢谢。 问候。

【问题讨论】:

  • 所有三个类都应该使用super(如果有的话)。这就是允许按照从继承树中推断的顺序调用每个函数的原因,而不是需要对特定方法的显式引用。

标签: python class oop inheritance multiple-inheritance


【解决方案1】:

parent1parent2,如果希望在协作多重继承设置中使用,应调用super

class parent1:
    def __init__(self):
        super().__init__()
        self.color = "Blue"

class parent2:
    def __init__(self):
        super().__init__()
        self.figure = "Triangle"

当您定义child 时,其方法解析顺序决定了首先调用哪个__init__,以及确定每次调用它时引用哪个类super()。在您的实际示例中,

class child(parent1,parent2):
    pass

parent1.__init__ 被首先调用(因为child 不会覆盖__init__),它对super() 的使用是指parent2。如果您改为定义

class child2(parent2, parent1):
    pass

那么parent2.__init__会首先被调用,它对super()的使用会引用parent1

super() 不是用来确保调用object.__init__(它不做任何事情),而是object.__init__ 存在以便它可以在@ 链中被调用一次987654341@ 通话结束。 (object.__init__ 本身使用super,因为它保证是任何其他类的方法解析顺序中的最后一个类。)

【讨论】:

  • 就是这样。在这种特殊情况下,即使我只是在 parent1 上编写 super().__init__() 也可以工作,因为当 parent1 被“调用”时, super().__init__() 指的是父 2。非常感谢。
  • 如果super().__init__ 是你的__init__ 唯一做的事情,它可以保持未定义,因为你只是明确地调用了无论如何都会被隐式调用的东西。
猜你喜欢
  • 2017-01-12
  • 2020-01-27
  • 2020-07-05
  • 2012-01-31
  • 1970-01-01
  • 2021-11-28
  • 2021-05-07
  • 1970-01-01
  • 2012-08-08
相关资源
最近更新 更多