【问题标题】:Why in Multiple Inheritance only one class init method get called [duplicate]为什么在多重继承中只有一个类init方法被调用[重复]
【发布时间】:2017-07-14 10:24:07
【问题描述】:

在模块 a.py 中

class Foo(object):
    def __init__(self):
        self.foo = 20

class Bar(object):
    def __init__(self):
        self.bar = 10

class FooBar(Foo, Bar):
    def __init__(self):
        print "foobar init"
        super(FooBar, self).__init__()
a = FooBar()
print a.foo
print a.bar

在多重继承中,只有第一个类的 init 方法被调用。 有没有办法在多重继承中调用所有的init方法,这样我就可以访问所有的类实例变量

输出

foobar init
20
Traceback (most recent call last):
File "a.py", line 16, in <module>
    print a.bar
AttributeError: 'FooBar' object has no attribute 'bar'

无法访问Bar类变量bar

【问题讨论】:

  • @Rawing 但是如果只有一个父类init需要参数而另一个父类没有任何参数,那么如何使用super关键字调用所有类的init
  • @Kallz 在这种情况下,您不使用super。你会做Foo.__init__(self); Bar.__init__(self, parameter)

标签: python python-2.7 multiple-inheritance


【解决方案1】:
class Foo(object):
def __init__(self):
    super(Foo,self).__init__()
    self.foo = 20

class Bar(object):
def __init__(self):
    super(Bar,self).__init__()
    self.bar = 10


class FooBar(Bar,Foo):
def __init__(self):
    print "foobar init"
    super(FooBar,self).__init__()



a = FooBar()
print a.foo
print a.bar

super() 调用会在每一步的 MRO(方法解析顺序)中找到 /next 方法/,这就是为什么 Foo 和 Bar 也必须拥有它的原因,否则执行会在 Bar 结束时停止。初始化

【讨论】:

  • 如果Foo__init__ 需要一个参数怎么办?这段代码会崩溃。使用 super 调用 unknown(到 Bar)构造函数是一个可怕的想法(除非你的类是有意 用于钻石继承)。
  • 我知道 Foo 的 init 是否需要一个参数它会崩溃,但这里我们不需要任何参数,如果 Foo 的 init 需要一个参数 i将通过 super(Bar,self).__init__(PARAMETER) 传递它。 @Rawing
猜你喜欢
  • 2018-01-05
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
相关资源
最近更新 更多