【问题标题】:Where to put required behavior on close in Python在 Python 中关闭所需行为的位置
【发布时间】: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


    【解决方案1】:

    如果您只需要确保程序关闭时文件已经消失,那么您应该使用atexit 模块。在其他情况下,您应该始终使用选项 1,原因在 this article.

    中列出

    【讨论】:

    • 顺便说一句,我已经更新了主帖以反映在代码继续之前必须删除文件。
    • 哦,我没有意识到你在使用 with 语句,哎呀。
    【解决方案2】:

    您的类应该是context manager,并且您应该将文件删除放在__exit__ 方法中。您已经在使用with 语句,只是您定义的类无法使用它,因为它缺少必需的__enter____exit__ 方法。

    【讨论】:

      猜你喜欢
      • 2022-11-25
      • 2021-12-20
      • 2021-03-19
      • 2017-02-06
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多