具有附加属性的多重继承

时间:2013-08-27 06:04:01

标签: python multiple-inheritance

处理这样的继承结构的最佳方法是什么:

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)

修改

工作回答,感谢Daniel Roseman。

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)

1 个答案:

答案 0 :(得分:3)

最好的方法是始终确保使用*args, **kwargs语法定义和调用方法。这意味着他们将获得他们需要的参数而忽略其余的参数。