处理这样的继承结构的最佳方法是什么:
class A(object):
def __init__(self):
print('A')
class B(A):
def __init__(self, foo):
super(B, self).__init__()
self.foo = foo
print('B')
class C(A):
def __init__(self, bar):
super(C, self).__init__()
self.bar = bar
print('C')
class D(B, C):
def __init__(self, foo, bar):
super(D, self).__init__(foo, bar)
本质上,我希望能够调用:
>>> d = D('bar', 'ram ewe')
>>> d.foo
'bar'
>>> d.bar
'ram ewe'
目前,加super(D, self).__init__(foo, bar)
息TypeError: __init__() takes exactly 2 arguments (3 given)
编辑
工作的答案,感谢丹尼尔罗斯曼。
class A(object):
def __init__(self, *args, **kwargs):
print('A')
class B(A):
def __init__(self, foo, *args, **kwargs):
super(B, self).__init__(*args, **kwargs)
self.foo = foo
print('B')
class C(A):
def __init__(self, bar, *args, **kwargs):
super(C, self).__init__(*args, **kwargs)
self.bar = bar
print('C')
class D(B, C):
def __init__(self, foo, bar, *args, **kwargs):
super(D, self).__init__(foo, bar, *args, **kwargs)