这个
copy
模块可能是您需要的:
密码
def method_a(self):
return copy.copy(self)
更精细的控制:
在各种情况下,您可能只需要复制一些参数,可以使用
unpacking of argument lists
与…结合
getattr
要管理要复制的较长列表,请执行以下操作:
def method_a(self):
attributes_to_copy = ('value1', 'value2')
kwargs = {k: getattr(self, k) for k in attributes_to_copy}
return type(self)(**kwargs)
测试代码:
import copy
class X(object):
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
def method_a(self):
return copy.copy(self)
def method_b(self):
attributes_to_copy = ('value1', 'value2')
kwargs = {k: getattr(self, k) for k in attributes_to_copy}
return type(self)(**kwargs)
x1 = X(1, 2)
x2 = x1.method_a()
x3 = x1.method_b()
assert x1.value1 == x2.value1
assert x1.value1 == x3.value1