复制从Python中的实例构造基类
考虑以下代码:复制从Python中的实例构造基类,python,inheritance,copy-constructor,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(
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
初始化基类的python方法是什么?如果我用
super().__init__(abc.a, abc.b, abc.c)
每次我向ABC添加内容时,我都必须更改ABC
。我能做的就是使用
self.__dict__.update(abc.__dict__)
但是,当
ABC
使用与dict
不同的底层实现时(例如\uuuuuuuuuuuuuuuuuuu
),这会让人感觉笨拙,并且会中断。有其他方法吗?如果将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的“责任”
如果您在开始时将参数指定给
ABCD
,您可以这样做:\uuuu init\uuuu(self,d,*args,**kargs)
然后super()。\uuu init\uuuuu(*args,**kargs)
@Holt:那么我需要使用abc=abc(4,abc.a,abc,abc)
,而不是abc=abc(4,abc)
,因此,强制abc
的用户手动解包abc
。对不起,我没有阅读您的代码结尾,我以为您想直接执行abc(4,1,2,3)
。是的,通常情况下都是这样。但是,在我的特殊情况下,我需要从ABC
继承ABC
,因此它的行为类似于ABC
的子类,用户可以直接访问ABC
的所有属性。在这种情况下,我将编写一个方法(ABC)来执行此复制。参见编辑above@eran如果您从外部库继承一个巨大的类,那么复制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