上下文管理器(context manager)用于规定某个对象的使用范围。进入或者离开该使用范围,会有特殊操作被调用。它的语法形式是with...as...
我们经常会进行这样的操作:打开文件,读写,关闭文件。偶尔会忘记关闭文件,使用上下文管理器可以在不需要文件的时候,自动关闭文件。
1 with ...as...示例
with open("test.txt", "w") as file:
print(file.closed)
file.write("with as test!")
print(file.closed)使用上下文管理器,当隶属的程序块执行结束的时候(也就是不再缩进),上下文管理器自动关闭了文件 (file.closed查询文件是否关闭)。使用缩进规定了文件对象f的使用范围。
当使用上下文管理器时,Python在进入程序块之前调用对象的__enter__()方法,在结束程序块的时候调用__exit__()方法。对于文件对象file来说,它定义了__enter__()和__exit__()方法(通过dir(file)可查看)。在file的__exit__()方法中,调用了self.close()语句。
2 自定义上下文管理器
所谓自定义上下文管理器,其实就是自己定义__enter__()和__exit__()方法。我们需要创建一个类,然后在其中定义__enter__()和__exit__()。
class test:
def __init__(self, input):
self.text = input
def __enter__(self):
self.text = "call __enter__ " + self.text
return self #return an object
def __exit__(self,exc_type,exc_value,traceback):
self.text = self.text + " call __exit__"
with test("hello") as mytest:
print(mytest.text)
print dir(mytest)
print(mytest.text)
本文介绍了Python中的上下文管理器概念及其应用。通过with语句可以方便地管理资源,如文件的自动打开与关闭。此外,还展示了如何自定义上下文管理器,通过实现__enter__和__exit__方法来增强程序的功能。
930

被折叠的 条评论
为什么被折叠?



