【发布时间】:2016-07-19 04:57:27
【问题描述】:
我有一个类在构建时创建一个临时文件,一旦完成就应该删除它。请注意,我了解创建临时文件可能不是解决原始问题的理想解决方案,但假设无法更改。除此之外,代码将在整个程序过程中运行多次。
哪个是删除文件最理想的位置?
选项 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()
选项 2:
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 对我来说似乎更具可读性。
【问题讨论】:
标签: python class constructor resources destructor