python 中关于with...as的用法

python中的with...as类似于try...except......finally...其用法是

with A() as b:

        suite

block

其中A是一个类,该类中必须包含两个函数__enter__(),和__exit__()  ,b为函数__enter__()函数的返回值,当执行with A() as b: 时,首先会创建一个A 的一个临时对象,

然后调用__enter__()函数,若__enter__()函数执行出现异常直接终止,并将返回值赋值给b,接着执行suite,若suite中存在异常会中断执行函数__exit__(),

若__exit()__函数返回True,则接着执行block,否者终止,

若不存在异常,执行完suite后,执行函数__exit__(),最后执行block。

类如:

1.

class open:
    def __enter__(self):
        print 'return'
        return 2
    def __exit__(self,type,value,traceback):     #若有异常会将异常的信息赋值给exit的参数type,value,traceback,否者为None
        return isinstance(value,NameError)    #如果出现NameError返回true
with open() as s:
    print s
    print e
    print 'hello'
print 'nihao'

执行结果:

return
2
nihao

2.

class open:
    def __enter__(self):
        print 'return'
        return 2
    def __exit__(self,*args):    #异常的信息以tuple形式赋给args

        print args   #隐藏了返回值false

with open() as s:
    print s
    print e
    print 'hello'
print 'nihao'

结果:

return
2
(<type 'exceptions.NameError'>, NameError("name 'e' is not defined",), <traceback object at 0x0000000002EE43C8>)


Traceback (most recent call last):
  File "E:\python-workplace\t.py", line 10, in <module>
    print e
NameError: name 'e' is not defined

因为exit的返回值为false

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值