python上下文管理器的基本介绍

本文教程操作环境: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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。