复制从Python中的实例构造基类

时间:2014-05-10 11:17:30

标签: python inheritance copy-constructor

考虑以下代码:

class ABC:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class ABCD(ABC):
    def __init__(self, abc, d):
        # How to initialize the base class with abc in here?
        self.d = d

abc = ABC(1, 2, 3)
abcd = ABCD(abc, 4)
print(abcd.a)

使用abc初始化基类的Pythonic方法是什么?如果我用过

super().__init__(abc.a, abc.b, abc.c)

每次向ABCD添加内容时,我都必须更改ABC。我能做的就是使用

self.__dict__.update(abc.__dict__)

然而,当ABC使用与dict不同的基础实现(例如__slots__)时,这会感到笨拙并且会中断。还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

如果将类型为abc的对象传递给构造函数,也许你应该将abc作为字段而不是继承。

e.g。也许:

class ABC:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

class ABCD:
    def __init__(self, abc, d):
        # How to initialize the base class with abc in here?
        self.abc = abc

abc = ABC(1, 2, 3)
abcd = ABCD(abc, 4)
print(abcd.abc.a)

根据你的评论,我会编写复制ABC部分的方法。这样,这种方法就是ABC的“责任”。

class ABC:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def copy_init(other):
        self.a = other.a
        self.b = other.b
        self.c = other.c

class ABCD(ABC):
    def __init__(self, abc, d):
        self.copy_init(abc)
        self.d = d