我想创建一个类,它有一个方法来重置其属性,但我需要将重置之前的数据保存在某个列表中。
我尝试了以下代码:
class Foo:
feature1 = 'hey'
feature2 = 10
def reset(self):
self.feature1 = None
self.feature2 = None
some_list = []
foo = Foo()
print(foo.feature1)
print(some_list)
some_list.append(foo)
foo.reset()
print(foo.feature1)
print(some_list[0].feature1, some_list[0].feature2)
但它打印出这个:
hey
[]
None
None None
有办法复制吗?
最佳答案
我建议您尝试创建新实例而不是重置。并且还要使属性成为实例的一部分,而不是类的一部分。
像这样定义你的类:
class Foo:
def __init__(self):
self.feature1 = 'hey'
self.feature2 = 10
def __repr__(self):
return '[{}|{}]'.format(self.feature1, self.feature2)
然后运行这些行:
some_list = []
foo = Foo()
foo.feature1 = 'hey_1'
some_list.append(foo)
print(some_list)
foo = Foo() # will be a new instance
foo.feature1 = 'hey_2'
some_list.append(foo)
print(some_list)
您将得到以下输出:
[[hey_1|10]]
[[hey_1|10], [hey_2|10]]
关于python - 如何在对象实例中保存当前状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53116030/