码迷,mamicode.com
首页 > 编程语言 > 详细

python的with

时间:2017-08-08 22:59:19      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:管理   返回值   self   init   context   运行   lock   elf   访问   

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

标签:管理   返回值   self   init   context   运行   lock   elf   访问   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!