在Python中,将所需行为放在关闭位置

在Python中,将所需行为放在关闭位置,python,class,constructor,resources,destructor,Python,Class,Constructor,Resources,Destructor,我有一个类,它在构造时创建一个临时文件,并在完成后将其删除。请注意,我理解创建临时文件可能不是解决原始问题的理想方法,但我认为这是无法更改的。同时,代码将在整个程序过程中多次运行 删除文件最理想的位置是哪个 选项1: import sys import os class Foo: def __init__(self): self.file = open("temp.txt", 'wb') def do_something(self): # ..

我有一个类,它在构造时创建一个临时文件,并在完成后将其删除。请注意,我理解创建临时文件可能不是解决原始问题的理想方法,但我认为这是无法更改的。同时,代码将在整个程序过程中多次运行

删除文件最理想的位置是哪个

选项1:

import sys
import os

class Foo:
    def __init__(self):
        self.file = open("temp.txt", 'wb')

    def do_something(self):
        # ...

    def close(self):
        self.file.close()
        os.remove("temp.txt")
while True:
    foo = Foo()

    foo.do_something()
    foo.close()
import sys
import os

class Foo:
    def __init__(self):
        self.file = open("temp.txt", 'wb')

    def do_something(self):
        # ...

    def __del__(self):
        self.file.close()
        os.remove("temp.txt")
while True:
    with Foo() as foo:
        foo.do_something()
选项2:

import sys
import os

class Foo:
    def __init__(self):
        self.file = open("temp.txt", 'wb')

    def do_something(self):
        # ...

    def close(self):
        self.file.close()
        os.remove("temp.txt")
while True:
    foo = Foo()

    foo.do_something()
    foo.close()
import sys
import os

class Foo:
    def __init__(self):
        self.file = open("temp.txt", 'wb')

    def do_something(self):
        # ...

    def __del__(self):
        self.file.close()
        os.remove("temp.txt")
while True:
    with Foo() as foo:
        foo.do_something()

我对使用选项2犹豫不决,因为我听说在析构函数中放入所需操作是一种不好的做法。但是,选项2对我来说更具可读性。

如果您只需要确保程序关闭时文件已消失,那么您应该使用该模块。在其他情况下,出于

中概述的原因,您应始终使用选项1。如果您只需要确保程序关闭时文件已消失,则应使用该模块。在其他情况下,出于

中概述的原因,您应该始终使用选项1。您的类应该是a,并且您应该将文件删除放在
\uuuuuuu退出
方法中。您已经在使用
with
语句,只是您定义的类无法使用它,因为它缺少所需的
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法。您已经在使用
with
语句,只是您定义的类无法使用它,因为它缺少必需的
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,我更新了主帖,以反映在代码继续之前必须删除文件。哦,我没有意识到你在使用with语句,oops。顺便说一下,我更新了主帖,以反映在代码继续之前必须删除文件。哦,我没有意识到你在使用with语句,oops。