Python3:调用析构函数时如何保存数据

Python3:调用析构函数时如何保存数据,python,python-3.x,file,destructor,Python,Python 3.x,File,Destructor,实际上我有一个关于蟒蛇3的问题。我想在调用析构函数时将类的属性保存在一个文件中。我该怎么做 我试着这样做: def __del__: file = open("test.dat", "w") file.write("Hello") file.close() 那个代码不起作用。我已经读过,你不应该使用它,但我实际上没有找到一个可行的替代方案。有人能帮我吗 提前谢谢 要使用该代码,它必须是类的一部分: class Test(): def __init__(self):

实际上我有一个关于蟒蛇3的问题。我想在调用析构函数时将类的属性保存在一个文件中。我该怎么做

我试着这样做:

def __del__:
   file = open("test.dat", "w")
   file.write("Hello")
   file.close()
那个代码不起作用。我已经读过,你不应该使用它,但我实际上没有找到一个可行的替代方案。有人能帮我吗


提前谢谢

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

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
,则要使用该代码,它需要是类的一部分:

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

此方法的用例是什么?您希望什么时候保存数据?问题是,我需要保存类的一些属性,因为当我再次启动python脚本时,我需要一些属性。因此,当我再次开始创建类时,我需要将旧数据保存在文件中并从中读取?您希望什么时候保存数据?问题是,我需要保存类的一些属性,因为当我再次启动python脚本时,我需要一些属性。因此,当我再次开始创建类时,我需要将旧数据保存在文件中并从中读取。当我这样做的时候,我总是会得到一个错误:NameError:name'open'没有定义只是看看,你使用的是不是3.4之后的版本(例如3.5或3.6?)。如果是这样的话:首先,谢谢你的回答。当我这样做的时候,我总是会得到一个错误:NameError:name'open'没有定义只是看看,你使用的是不是3.4之后的版本(例如3.5或3.6?),如果是这样的话: