Python:从父类(super class)构造多重继承子类实例

标签 python inheritance type-conversion multiple-inheritance

所以我的项目中有两个类:CircuitSubCircuit。在某些时候,我可能需要从Circuit构造一个SubCircuit。有没有比下面最后 4 行所做的更优雅的方法?例如,Circuit 可能会在某个时刻获得一些新属性,这意味着转换也需要更新 - 基本上会引发错误。

class Gate(abc.ABC):
    def __init__(self, size):
        self.in_ports = (InPort(self),) * size
        self.out_ports = (OutPort(self),) * size


class Circuit:
    def __init__(self, size):
        self.input = (OutPort(self),) * size
        self.output = (InPort(self),) * size
        self.gates = []

    # ... some other stuff that messes around with these attributes


class SubCircuit(Gate, Circuit):
    def __init__(self, circuit=None):
        Gate.__init__(self, size)
        Circuit.__init__(self, size)

        if circuit is not None:
            self.gates = circuit.gates
            self.input = circuit.input
            self.output = circuit.output

最佳答案

错误已经存在 - 当您执行 self.gates = Circuit.gates 时,Circuit.gates 是一个列表,您将两个引用都指向同一个列表 - 并且如果此列表在原始电路上更新,则此更新将反射(reflect)在您的子电路实例中。

我认为最明智的模式是,如果您有一个用于更新自己的电路实例,则为该类提供一个备用构造函数:

from copy import copy
class SubCircuit(Gate, Circuit):
    def __init__(self, size):
        Gate.__init__(self, size)
        Circuit.__init__(self, size)

    @classmethod
    def from_circuit(cls , circuit, size):
        self = SubCircuit(size)
        for key, value in circuit.__dict__.items():
             setattr(self, key, copy(value))
        return self

一件“正确”的事情是让类 __init__ 和其他方法通过协作使用 super() 相互调用,而不是通过显式调用 then name - 但是,如果您的类和子类固定为这 3 个,那可能有点过分了,因为 Python 的对象不处理传递给其自己的 __init__ 方法的额外参数。 (因此,您必须在基类 __init__ 中验证它们是否是方法解析顺序上 object 之前的最后一个,并吞下剩余的参数)

关于Python:从父类(super class)构造多重继承子类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42890775/

相关文章:

c++ - 从我的类(class)转换为 int

c++ - 从 std::function 继承,语法和用法?

c++ - const 双指针参数的非常量指针参数

python - 将 numpy 数组值从零更改为 -1

Python网络爬虫找不到存在的关键字

C++ : How to bind inherited methods only to parent classes?

c++ - 尝试从 C++ 中的构造函数继承类时出错

ios - 我应该如何从 json 字符串中读取数据?苹果手机

python - Pandas:转换为数字,必要时创建 NaN

python - Pytorch Batchnorm 层与 Keras Batchnorm 不同