千万 ***A``C``(C, A, B, object)``super(A, self).__init__``B.__init__
对于这些情况,你不希望使用合作继承,而是直接引用A.__init__
和B.__init__
替代。super()
仅在您所调用的方法具有相同签名时使用, 否则将使用*args
和吞下不受支持的参数**vargs
。在这种情况下,只super(C, self).__init__()
需要一个调用,MRO顺序中的下一个类将负责该调用的链接。
换种说法:使用时super()
,您无法知道MRO中的下一个类,因此该类更好地支持传递给它的参数。如果不是这种情况,请 不要 使用super()
。
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)
使用合作社super()
:
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)