您当前的位置: 首页 >  Python

少林码僧

暂无认证

  • 3浏览

    0关注

    317博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

python with用法详解

少林码僧 发布时间:2019-01-25 16:42:07 ,浏览量:3

# coding:utf8
def except_try():
    try:
        print("start")
        #raise KeyError
        raise IndexError
        return 1
    except KeyError:
        print("key error 异常时执行")
        return 2
    else:
        print("other error")
        return 3
    finally:
        print("总会执行")
        return 4
# 上下文管理协议
class WithDemo:
    def __enter__(self):
        print("调用with开始时执行")
        # return self
        # 获取资源

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("调用with结束时执行")
        #用于释放资源

    def do_something(self):
        print("do something")

if __name__ == '__main__':

    try:
        print("start")
        raise KeyError
        # raise IndexError
    except KeyError:
        print("key error 异常时执行")
    else:
        print("other error")
    finally:
        print("总会执行")

    # return 压栈
    print(except_try()) #4

    print("====================with====================")

    with WithDemo() as wd:
        wd.do_something()

with进阶

# coding:utf8
import contextlib

@contextlib.contextmanager
def write_file(file):
    print(file," file open")
    print("文件操作中。。。") # 最先执行
    # raise IOError
    yield {}
    print("file close") #最后执行

if __name__ == '__main__':
    with write_file("/usr/local/data/test") as f:
        print("start...")
关注
打赏
1661398670
查看更多评论
立即登录/注册

微信扫码登录

0.0384s