【发布时间】: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