python - 理解 Python 中的 super

标签 python inheritance super diamond-problem

你能给我解释一下如何用 Python 编写致命钻石吗?我看到许多不使用构造函数参数的类似代码示例,但是一旦我开始使用参数,事情就开始变得困惑...

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

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

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

class D(B, C):
    def __init__(self, a, b, c, d):
        self.d = d
        # How do I pass a and b to B.__init__
        # and a and c to C.__init__
        # using super() ?
        super().__init__(a, b, c) #???

d = D(1, 2, 3, 4)

最佳答案

最简单的方法可能是每个子类都接受一个 kwargs 字典,并将其传递给上层:

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

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

class C(A):
    def __init__(self, c, **kwargs):
        self.c = c
        super().__init__(**kwargs)

class D(B, C):
    def __init__(self, d, **kwargs):
        self.d = d
        super().__init__(**kwargs)

d = D(a=1, b=2, c=3, d=4)

print(d.a, d.b, d.c, d.d)
# 1 2 3 4

在每次调用时,__init__ 获取它需要的参数,并将剩余的参数传递给父类。唯一的缺点是您必须将参数作为关键字传递。

关于python - 理解 Python 中的 super ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61456385/

相关文章:

c# - 继承类属性顺序

java - super (空): what does this mean?

java - 我如何访问 super-super 类,在 Java 中? [里面的小例子]

Python:os.path.isdir/isfile/exists 不起作用,当它们应该返回 True 时返回 False

Python Spacy 相似性没有循环?

python - 生命计数器不断重置

python - 如何在 Python 中使用 Selenium 打开 chrome 开发者控制台?

Hibernate 注释以排除基类中的字段

c# - 如何用抽象基础修复 "CA1810: Initialize reference type static fields inline"...?

java - 如何从二级继承类调用基类方法?