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

 

你可能感兴趣的:(python,with...as的用法)