python - 如何在对象实例中保存当前状态?

标签 python

我想创建一个类,它有一个方法来重置其属性,但我需要将重置之前的数据保存在某个列表中。

我尝试了以下代码:

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/

相关文章:

Python SFTP 彭博数据许可证 - Paramiko

python - Flask 在通过 Gunicorn 运行时无法在模板文件夹中找到 HTML 文件

python - 在 Pandas 中用自身的功能替换列?

python - 将变量传递给 pytest 中的依赖测试

python - Pandas 合并无法提取公共(public)索引值

python - 在显示转换为 float 的图像时出现奇怪的 matplotlib 行为

python - 使用管道直接从 np.array 高效地编写电影

python - 设置 Bloomberg Python API 时出现 ImportError _versionhelper

python - Pandas DataFrame 的组合与子类

python - 从多个 shell 子进程中非阻塞实时读取 (Python)