python上下文管理器的使用

版权声明:本文为博主原创文章,转载需要注明源地址 https://blog.csdn.net/qq_33512078/article/details/79017907

python中上下文管理器一般通过with来使用
如:

with open('1.txt') as fp:
    do something

书写上下文管理器相当于书写上例代码中的open函数

先给出使用方法:

with test(5) as b:
    print b

一般有两种编写方法(第二种是大家嫌第一种烦,给出的简化版本):

class test:
    def __init__(self, value):  # 接收test方法传进的参数
        self.value = value

    def __enter__(self):  # 执行上下文管理器包裹代码之前的准备工作
        print('enter')
        return self.value  # 返回给上述的b变量

    def __exit__(self, exc_type, exc_val, exc_tb): # 执行上下文管理器包裹代码之后的清理工作
        print('gone')
import contextlib

 @contextlib.contextmanager
 def test(a):
     print 'enter'
     try:
         yield a  # 将a的值返回给使用方法中的b变量
     except:
         raise
     finally:
         print 'gone'

猜你喜欢

转载自blog.csdn.net/qq_33512078/article/details/79017907