美文网首页
python中的with...as

python中的with...as

作者: amyhy | 来源:发表于2017-11-12 16:48 被阅读16次

with如何工作?
基本思想是with所求值的对象必须一个enter方法和exit方法。
紧跟with后面的语句被求值后,返回对象的enter()方法被调用吗,这个方法返回值将被赋值给as后面的变量。当with后面的代码全部被执行完毕之后,将调用前面返回对象的exit方法。

# encoding: utf8

class Sample:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print "in __enter__()"
        self.name = "yoyo"
        return self.name

    def __exit__(self, exc_type, exc_val, exc_tb):
        print "in __exit__()"


with Sample("hy") as sample:
    print sample

运行代码,输出如下:

in __enter__()
yoyo
in __exit__()

正如结果:
1.enter()方法被执行
2.enter()方法返回的值-这个例子中是“yoyo”,赋值给变量‘sample’
3.执行代码块,打印变量“sample”的值为“yoyo”
4.exit()方法被调用

相关文章

网友评论

      本文标题:python中的with...as

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