问题
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