美文网首页
python - with xxx as xxxx 语法了解

python - with xxx as xxxx 语法了解

作者: 安静1337 | 来源:发表于2018-03-29 00:53 被阅读37次

简介

python中,with-as语法一般用于资源关闭的情况,可以当成try - except - finally的一种优雅写法,不需要我们自己频繁编写关于释放资源的代码。

以打开文件资源为例,通常的写法:

try:
    f = open("xxx")
except:
    print("except when open file")
    exit(0)

try:
    do ...
except:
    do ...
finally:
    f.close()

(PS:python中,tryif语块等并没有类似于其他语言中的作用域概念)

但是,用with ... as ...写法,可以变成这样:

with open("xxx") as f:
    do ...

原理

with-as表达式语法需要python中class的支持:

class TEST:
    def __enter__ (self):
        do ...
        return somethings

    def __exit__ (self, type, value, traceback):
        do ... (finally)

当执行with-as时(with TEST() as t),首先调用__enter__函数,
然后把该函数的return值返回给as后面指定的变量。之后执行执行正常代码块,
最终,流程正常完毕或有异常状况,都会执行__exit__函数。

后记

总之,with-as是python在语言级别上实现了一种try-except-finally的语法糖

相关文章

网友评论

      本文标题:python - with xxx as xxxx 语法了解

      本文链接:https://www.haomeiwen.com/subject/qyupcftx.html