ITPub博客

首页 > IT职业 > IT职场 > python上下文管理器的基本介绍

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

IT职场 作者:mac_xuyi 时间:2021-09-11 10:00:21 0 删除 编辑

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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4273/viewspace-2830815/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-12

  • 博文量
    75
  • 访问量
    497