上下文管理器定义设置/清理功能__enter__
and __exit__
。惊人的。我想保留一个作为成员变量。当我的类对象超出范围时,我希望执行此清理操作。据我所知,这基本上是 C++ 构造函数/析构函数自动发生的行为。
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.
我给班级一个close
函数如果有意义,然后使用closing上下文管理器:
class MyClass(object):
def __init__(self):
self.resource = acquire_resource()
def close():
release_resource(self.resource)
然后像这样使用它:
from contextlib import closing
with closing(MyClass()) as my_object:
# use my_object
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)