python上下文管理器的基本介绍
发布时间:2024-09-09 10:21:29

本教程的操作环境:windows7系统,Python 3.9.1,DELL G3电脑。
1、概念
上下文管理器是支持上下文管理器协议的对象 __enter__() 和 __exit__() 方法。
2、基本语法
withEXPRasVAR: BLOCK
3、两种方法
__enter__:在进入 with 在语法块调用之前,返回值将被赋值 with 的 target
__exit__:在退出 with 调用语法块时,一般用于异常处理
4、实例
importtime
classdemo:
def__init__(self,label):
self.label=label
def__enter__(self):
self.start=time.time()
def__exit__(self,exc_ty,exc_val,exc_tb):
end=time.time()
print('{}:{}'.format(self.label,end-self.start))
withdemo('counting'):
n=10000000
whilen>0:
n-=1
#counting:1.36000013351以上就是python上下文管理器的基本介绍,在初步掌握with方法后,可以与上下文管理器结合使用,也许会有新的收获。
