python with 使用说明

2016-10-15 python

参考:http://effbot.org/zone/python-with-statement.htm

一旦知道with段用于解决什么问题,那使用with语法将会非常简单:

如下片段:

    set things up #打开一个文件或请求外部资源

    try :

        do something

    finally :

        tear things down #关闭文件或释放资源

    try-finally结构保证"tear things down"一直都会被执行,不管"do something"有没有完成


如果要经常使用这个结构,可以考虑使用如下结构:

    def controlled_execution(callback) :

        set things up

        try :

            callback(thing)

        finally :

            tear things down

    def my_fn(thing) :

        do something


    controlled_execution(my_fn)

但是看起来有点啰嗦, 也可以采用如下方式:

    def controlled_execution() :

        set things up

        try :

            yield thing

        finally :

            tear things down


    for thing in controlled_execution() :

        do something in thing

但你只要执行一次函数时,也要使用loop就有点奇怪了

python团队使用如下结构来替代:

    class controlled_execution :

        def __enter__(self) :

            set things up

            return thing

        def __exit__(self, type, value, traceback) :

            tear things down

    with controlled_execution() as thing :

        some code

当with执行时,python执行__enter__方法,返回值给thing,

然后执行some code, 不管some code执行成功与否,执行完调用__exit__方法;

如果要抑制异常抛出,可以使__exit__()返回True,如忽略TypeError:

    def __exit__(self, type, value, traceback) :

        return isinstance(value, TypeError)

打开一个文件,处理里面内容然后保证它被关闭,可以使用如下代码:

    with open("x.txt") as f :

        data = f.read()

        do something with data

    

标签: python with

评论(0) 浏览(2352)

Powered by EMLOG Copyright @ 深圳市炽旗科技 版权所有. 闽ICP备14012694号-2