python - 在同一个python类中保留对象副本的最佳方法
问题描述
我面临的问题是我有一个对象A
,并且在该对象中我需要保留其A
自身的副本,我可以在不影响原始对象的情况下对其进行修改。例如,像这样:
class MyClass():
def __init__(self, value, copy=False, **kwargs):
self.value = value
if not copy:
self.A_copy = MyClass(copy=True)
# Do something with the other arguments
def expensive_operation(self, *args, **kwargs):
# Do expensive operation that changes properties of the instance
pass
但是,我不断收到可能与此代码有关的内核错误。我需要这样做的原因是因为我需要MyClass
为最终用户保留一个实例,而在后台我需要做一个昂贵的操作来改变实例的属性。假设您不能将昂贵的操作移到类之外,我可以通过哪些方式MyClass
在原始实例中保留实例的副本?创建装饰器会是更好的策略吗?