上下文管理器定義安裝/清除功能__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.