Multiple inheritance in python3 with different signatures
我有三个班:
我的代码努力:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class A(object): def __init__(self, a, b): super(A, self).__init__() print('Init {} with arguments {}'.format(self.__class__.__name__, (a, b))) class B(object): def __init__(self, q): super(B, self).__init__() print('Init {} with arguments {}'.format(self.__class__.__name__, (q))) class C(A, B): def __init__(self): super(A, self).__init__(1, 2) super(B, self).__init__(3) c = C() |
产生错误:
1 2 3 4 5 6 | Traceback (most recent call last): File"test.py", line 16, in <module> c = C() File"test.py", line 13, in __init__ super(A, self).__init__(1, 2) TypeError: __init__() takes 2 positional arguments but 3 were given |
号
我发现了这个资源,它用不同的参数组解释了多个继承,但是他们建议使用
除非你知道自己在做什么,否则不要使用
对于这些情况,您不希望使用合作继承,而是直接引用
换一种说法:当您使用
直接调用基
1 2 3 4 5 6 7 8 9 10 11 12 13 | class A(object): def __init__(self, a, b): print('Init {} with arguments {}'.format(self.__class__.__name__, (a, b))) class B(object): def __init__(self, q): print('Init {} with arguments {}'.format(self.__class__.__name__, (q))) class C(A, B): def __init__(self): # Unbound functions, so pass in self explicitly A.__init__(self, 1, 2) B.__init__(self, 3) |
使用合作
1 2 3 4 5 6 7 8 9 10 11 12 13 | class A(object): def __init__(self, a=None, b=None, *args, **kwargs): super().__init__(*args, **kwargs) print('Init {} with arguments {}'.format(self.__class__.__name__, (a, b))) class B(object): def __init__(self, q=None, *args, **kwargs): super().__init__(*args, **kwargs) print('Init {} with arguments {}'.format(self.__class__.__name__, (q))) class C(A, B): def __init__(self): super().__init__(a=1, b=2, q=3) |
号