首页 > 编程语言 > 详细

python的with

时间:2017-08-08 22:40:48      阅读:260      评论:0      收藏:0      [点我收藏+]

with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源。

比如文件使用后自动关闭、线程中锁的自动获取和释放等。

with open(test.txt, r) as f:
    for line in f:
        print(line)

运行机制

with VAR = EXPR:
    BLOCK

等价于

VAR = EXPR
VAR.__enter__()
try:
    BLOCK
finally:
    VAR.__exit__()

VAR对应一个上下文管理器(context manager)。

上下文管理器

实现了__enter__()和__exit__()两个方法的类就是一个上下文管理器。

class MyContextManager:
    def __enter__(self):
        print(before block run)
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(after block run)

使用上下文管理MyContextManager

with MyContextManager():
    print(run block)

输出如下:

before block run
run block
after block run

MyContextManager也可以接受参数

class MyContextManager:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __enter__(self):
        print(before block run)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(after block run)

    def show(self):
        print(my name is:, self.name)
        print(my age is:, self.age)

再次使用上下文管理MyContextManager

with MyContextManager(logan, 27) as myCM:
    myCM.show()

输出如下:

before block run
my name is: logan
my age is: 27
after block run

这里用到了一个as: with context_manager as target

target对应context_manager的__enter__()方法的返回值,返回值可以是context_manager自身,也可以是其他对象。

contextlib.contextmanager

 

python的with

原文:http://www.cnblogs.com/gattaca/p/7309192.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!