在 Python 中用字段解决钻石问题的最佳方法

问题描述

如果类中没有字段,Python 通过线性化方法解析顺序可以很好地解决菱形问题。但是,如果类有字段,那么如何调用超级构造函数?考虑:

class A:
    def __init__(self,a):
        self.a = a  # Should only be initialized once.

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

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

class D(C,B):
    def __init__(self,b,c):
        super().???  # What do you put in here.

对于我的用例,我确实有一个解决方案,因为在应用程序中 b 不能是 None,因此以下主要工作:

class A:
    def __init__(self,b):
        assert b is not None  # Special case of `b` can't be `None`.
        super().__init__(a)
        self.b = b

class C(A):
    def __init__(self,b=None):  # Special init with default sentinel `b`.
        if b is None:
            super().__init__(a)  # normally `C`'s super is `A`.
        else:
            super().__init__(a,b)  # From `D` though,`C`'s super is `B`.
        self.c = c

class D(C,B):  # Note order,`C`'s init is super init.
    def __init__(self,c):
        super().__init__(a,b)

def main():
    A('a')
    B('b',1)
    C('c',2)
    D('d',3,4)
    C('c2',5,6)  # TypeError: __init__() takes 2 positional arguments but 3 were given

这在很大程度上适用于 b 不能为 None 的特殊情况,但是如果直接调用 C__init__,它仍然有问题(请参阅上面的最后一行)。此外,您必须为多重继承修改 C,并且您必须以 C,B 的顺序继承。

==== 编辑 ===

另一种可能是手动初始化每个字段(这有点类似于 Scala 处理幕后字段的方式)。

class A0:
    def __init__(self,a):  # Special separate init of `a`.
        self._init_a(a)

    def _init_a(self,a):
        self.a = a


class B0(A0):
    def __init__(self,b):  # Special separate init of `b`.
        self._init_a(a)
        self._init_b(b)

    def _init_b(self,b):
        self.b = b


class C0(A0):
    def __init__(self,c):  # Special separate init of `c`.
        self._init_a(a)
        self._init_c(c)

    def _init_c(self,c):
        self.c = c

class D0(C0,B0):
    def __init__(self,c):  # Uses special separate inits of `a`,`b`,and `c`.
        self._init_a(a)
        self._init_b(b)
        self._init_c(c)

这种方法的缺点是它非常不标准,以至于 PyCharm 会发出关于不调用超级初始化的警告。

==== 结束编辑 ===

有更好的方法吗?

预先感谢您的帮助,霍华德。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...