让 class 在退出 `with` 语句的范围时执行任务

Making a class perform tasks when it exits scope of `with` statement

是否有我可以覆盖的 class 属性,使 class 的实例在退出 with 语句的范围之前执行某些操作?

例如,我们可以确保在完成处理后关闭文件句柄:

with open(PATH, 'wb') as f:
    f.write("SOME TEXT")

如果我写了一个 class 需要作家在 class 的生命周期中坚持这样的:

class MyWriter(object):

   def __init__(self, path):
       self.f = open(path, 'wb')
       self.buffer = ''

   def write(self, text):
       self.buffer += text
       # Just a toy example, naively relying on file system
       # page cache should outperform this 
       if len(self.buffer) >= 4096:
           self.flush()

   def flush(self):
       f.write(self.buffer)
       self.buffer = ''

   def close(self):
       self.flush()
       self.f.close()

然后我想在退出 with 的范围之前强制调用 .close() 并刷新:

with MyWriter(PATH) as mw:
    mw.write("SOME TEXT")

您要查找的术语是上下文管理器。这就是您的对象与 with 语句一起使用时所调用的对象。

有很好documentation on context managers in the official Python documentation. There is also some great background information and some good examples in PEP 343.