首页 > 解决方案 > 在 Python 3+ 多继承中使用 super 来初始化带参数的父类

问题描述

我知道它是如何工作的,它从MRO以前super的基类中找到方法。 因此,如果我有两个基类和,并让它们继承,我应该如何使用来初始化以及它们是否需要参数?像这样:
ABclass CsuperAB

class A:
    def __init__(self, a):
        self.a = a

class B:
    def __init__(self, b):
        self.b = b

class C(A, B): # inherit from A and B
    def __init__(self, c):
        A.__init__(self, a=1)
        B.__init__(self, b=2) # How to use super here?
        self.c = c 

如果我super在 each中使用class,我需要确保正确的继承顺序:

class A:
    def __init__(self, a):
        super().__init__(b=3)
        self.a = a

class B:
    def __init__(self, b):
        super().__init__()
        self.b = b

class C(A, B): # Here must be (A, B)
    def __init__(self, c, a):
        super().__init__(a=a)
        self.c = c

但这使得AB耦合,这真的很糟糕。我应该如何处理这种情况,即B初始化C?不使用super?最Pythonic的方式是什么?

标签: pythonsuper

解决方案


推荐阅读