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

4 投票
1 回答
2599 浏览
提问于 2025-04-18 06:06

考虑以下这段代码:

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)

每次我在ABC里添加东西时,都得改动ABCD。我可以这样做:

self.__dict__.update(abc.__dict__)

不过,这样做感觉很笨重,而且当ABC使用不同的底层实现(比如__slots__)时,这种方法就会出问题。有没有其他的替代方法?

1 个回答

1

如果你把一个类型为abc的对象传给构造函数,那么你可能应该把abc作为一个字段,而不是用继承的方式。

比如说:

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

撰写回答