如何在Python3中深度复制类对象



GIVEN

class A:
x = 4711
B = COPY(A)
setattr(B, "x", "0815")
print("A: %s; B: %s;" % (A.x, B.x))

目标

操作COPY,使得上面的代码片段导致

A: 4711; B: 0815;

用平实的话

通过什么方式可以深度复制类对象,使其与原始对象完全隔离。使用copy.deepcopy()交付

A: 0185; B: 0185;

所以这不是解决方案。

from copy import deepcopy
class A:
x = 123
def __init__(self):
self.f()
def f(self):
print("original function", self.x)
def g(self):
print("replacement function", self.x)
B = deepcopy(A)
B.x = 456
B.f = g
a = A()
b = B()

此示例打印:

replacement function 456
replacement function 456

显然,AB的属性xf具有相同的值。因此,正如您已经注意到的,copy.deepcopy对";复制";类对象。Python类对象似乎是singleton,因为A is deepcopy(A)就是True

因此,或者,您可以使用继承而不是复制:

class A:
x = 123
def __init__(self):
self.f()
def f(self):
print("original function", self.x)
def g(self):
print("replacement function", self.x)
class B(A):
pass
B.x = 456
B.f = g
a = A()
b = B()

打印:

original function 123
replacement function 456

像这样,我们可以在不影响A.xA.f的情况下更改B.xB.f

然而,isinstance(b, A)将是True,这可能是不希望的。此外,对A的类属性的更改将传播到其子B。因此,您只需先将原始A更改为伪A_,然后从中导出AB

class A:
x = 123
def __init__(self):
self.f()
def f(self):
print("original function", self.x)
def g(self):
print("replacement function", self.x)
A_ = A
class A(A_):
pass
class B(A_):
pass
B.x = 456
B.f = g
a = A()
b = B()

现在,isinstance(b, A)将是False,并且对A的类属性的更改将不会传播到B

最新更新