【问题标题】:Multiple Inheritance in Python ConfusionPython混淆中的多重继承
【发布时间】:2020-10-17 19:07:13
【问题描述】:

我有以下实现多重继承的代码。我希望调用super(base2,self).__init__() 打印--> "Printing from base2". 但程序什么也没打印;它也不会引发错误。

class base1:
    def __init__(self):
        print("printing from base1")
    
    def method(self,val):
        print("From method of base1", val)

class base2:
    def __init__(self):
        print("printing from base2")
    
    def method(self,val):
        print("From method of base2", val)
        
class child(base1, base2):
    def __init__(self):
        super(base2,self).__init__()  #is not working as expected
        
        
x = child() 

【问题讨论】:

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


【解决方案1】:

super 的调用期望子类作为它的第一个参数,而不是基类。你应该这样做

super(child, self).__init__()

但是,从 python 3.0 开始,你可以简单地做

super().__init__()

但这如何发挥多重继承的作用?这在this answer中解释得非常好

基本上,在您的情况下,将super 更改为适当的调用将产生base1 类'__init__ 调用。根据 MRO(方法解析顺序)。

如果您想调用base2__init__ 怎么办?好吧,您正在考虑在这种情况下直接调用 base2.__init__(),或者只是更改继承顺序。

class child(base2, base1):
    def __init__(self):
        super().__init__()

现在这将打印 base2 类的 __init__ 方法

【讨论】:

  • 感谢您的回复。如果我理解正确,在 super(classname,arg1, arg2..) 中,类名总是需要是继承层次结构中的子类。否则它将无法按预期工作。我理解正确吗?
  • @user3103957 super 的第一个参数中的classname 应该是将调用超类的类,因此super(foo, self) 将调用@987654337 的超类@.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多