【问题标题】:Python3: How to save data, when the destructor is calledPython3:调用析构函数时如何保存数据
【发布时间】:2017-10-10 06:02:43
【问题描述】:

我实际上有一个关于 Python3 的问题。我想在调用析构函数时将类的属性保存在文件中。我怎样才能做到这一点?

我试着这样做:

def __del__:
   file = open("test.dat", "w")
   file.write("Hello")
   file.close()

该代码不起作用。我已经读过,您不应该使用它,但实际上我没有找到可行的替代方法。有谁能够帮我?

提前致谢!

【问题讨论】:

  • 这个用例是什么?您希望在什么时候保存数据?
  • 嗯,问题是我需要保存类的一些属性,因为我需要一些属性,当我再次启动 python 脚本时。因此,当我再次开始创建类时,我需要将旧数据保存在文件中并从其中读取。

标签: python python-3.x file destructor


【解决方案1】:

要使用该代码,它必须是类的一部分:

class Test():
    def __init__(self):
        self.data = "Hello"

    def __del__(self):
        with open('text.txt', mode='w') as file:
            file.write(self.data)

if __name__ == '__main__':
    def something():
        obj = Test() # obj is deleted when function exits as it becomes out of scope
    something()

    obj = Test()
    del obj # also works because we explicitly delete the object

请注意,虽然此方法确实有效,但不能始终依赖它来始终执行,例如,如果调用了 sys.exit

【讨论】:

  • 首先感谢您的回答。当我这样做时,我总是收到错误:NameError: name 'open' is not defined
  • 刚刚看了一下,你用的是不是3.4以后的版本(比如3.5还是3.6?)如果是的话:stackoverflow.com/a/29737870/3185884
猜你喜欢
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 2020-11-01
  • 2011-04-16
  • 2022-01-18
  • 1970-01-01
相关资源
最近更新 更多