Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有附加属性的多重继承_Python_Multiple Inheritance - Fatal编程技术网

Python 具有附加属性的多重继承

Python 具有附加属性的多重继承,python,multiple-inheritance,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): supe

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

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)。\uuuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

编辑

工作答案,感谢丹尼尔·罗斯曼

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)

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

另请参见:。与公认的索赔答案相反,这是非常有可能的。读得好!谢谢,德尔南。谢谢:)工作得很有魅力!