从Python中的实例复制构造基类
考虑以下这段代码:
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