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

Python (171) 2023-07-22 00:06:13

本文教程操作环境: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方法后,可以结合上下文管理器的一起使用,说不定会有新的收获。

THE END

发表回复