首页 > 编程语言 > 详细

python的with...as用法

时间:2016-08-20 14:38:42      阅读:169      评论:0      收藏:0      [点我收藏+]

with...as叫做上下文管理器,作用是进入一个对象的作用域和离开时,可以执行执行一定的操作。这个操作是可以自己

设定的。

写个例子学习一下:

class test():
    def __init__(self):
        self.text = "hello"
    def __enter__(self):
        self.text += " world"
        return self              #这句必须要有,不然with ... as 时,as后面的变量没法被赋值
    def __exit__(self, arg1, arg2, arg3):     #一共四个参数,后面四个参数是好像是关于异常信息的,没研究过,先这样写着
        self.text += "!"
    def Print(self):
        print self.text

try:
    with test() as f:      #在with ... as的作用域内,进入会执行test()的__enter__()函数,出作用域执行__exit__()函数
        f.Print()
        raise StopIteration

except StopIteration:
    f.Print()

上面程序的运行结果是:

hello world
hello world!

1.即使发生了异常,只要出了with...as的作用域,__exit__()函数就会被执行

2.f的作用域并不局限于with ... as内

3.分析打印的结果,可以看出来,test类中函数的执行顺序是 __init__() -->__enter__() ---> __exit__()

 

参考:http://www.cnblogs.com/vamei/archive/2012/07/10/2582787.html

python的with...as用法

原文:http://www.cnblogs.com/abcdk/p/5790329.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!