您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python3中具有不同签名的多重继承

python3中具有不同签名的多重继承

千万 ***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()

__init__直接调用基本方法

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)
python 2022/1/1 18:32:51 有385人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶