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

288次阅读
没有评论

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

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、概念

上下文管理器就是支持上下文管理器协议的对象,实现了 __enter__() 和 __exit__() 方法。

2、基本语法

with EXPR as VAR:
    BLOCK

3、两种方法

__enter__:在进入 with 语法块之前调用,返回值会赋值给 with 的 target

__exit__:在退出 with 语法块时调用,一般用作异常处理

4、实例

import time
 
 
 
class demo:
 
    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))
 
 
 
with demo('counting'):
 
    n = 10000000
 
    while n > 0:
 
        n -= 1
 
 
 
# counting: 1.36000013351

以上就是python上下文管理器的基本介绍,大家在初步掌握with方法后,可以结合上下文管理器的一起使用,说不定会有新的收获。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-08发表,共计677字。
新手QQ群:570568346,欢迎进群讨论 Python51学习