Why in Multiple Inheritance only one class init method get called [duplicate]

不问归期 提交于 2019-12-12 04:09:55

问题


In Module 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

In multiple inheritances only first class init method getting called. Is there any way to call all init method in multiple inheritances, so I can access all classes instances variable

Output:

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'

unable to access Bar class variable bar


回答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

The super() call finds the /next method/ in the MRO(method resolution order) at each step, which is why Foo and Bar have to have it too, otherwise execution stops at the end of Bar.init.



来源:https://stackoverflow.com/questions/45100633/why-in-multiple-inheritance-only-one-class-init-method-get-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!