上下文管理器定义安装/清除功能__enter__
和__exit__
。真棒。我想保留一个作为成员变量。当我的类对象超出作用域时,我希望执行此清理。这基本上是我理解的行为是使用C++构造函数/析构函数自动发生的。Python上下文托管成员变量?
class Animal(object):
def __init__(self):
self.datafile = open("file.txt") # This has a cleanup function
# I wish I could say something like...
with open("file.txt") as self.datafile: # uh...
def makeSound(self):
sound = self.datafile # I'll be using it later
# Usage...
if True:
animal = Animal()
# file should be cleaned up and closed at this point.