python 中关于with...as的用法
来源:互联网 发布:unity3d运动的模型 编辑:程序博客网 时间:2024/06/05 06:05
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的用法
- Python中关于with open file as 的用法
- python 中 with as的用法
- Python中with...as的用法
- python中 with...as的用法
- python中with as 用法
- python中 with as 用法
- python中with as 用法
- python的with...as...用法
- python with as的用法
- python with as的用法
- 关于oracle中 with xx as 的用法
- python with...as...用法
- python with...as用法
- python with...as...用法
- python with...as...用法
- python with as 用法
- python with as用法
- Eclipse J2EE IDE 安装注意
- 图像梯度特征的常用算子:Sobel、Prewitt、Roberts
- C调用Python脚本文件里的函数
- 云计算(三十一)-hbase Java API
- 高手教你如何从零开始学游戏编程
- python 中关于with...as的用法
- flex android 5.0”来了!
- Python:使用Scrapy框架的ImagesPipeline下载图片如何保持原图片名称呢?
- hdu 3746 Cyclic Nacklace
- 同步GET方法下载图片
- 神网卡黑苹果PCI网卡
- jsoncpp在linux编译
- hashmap 工作原理
- Generic netlink编程入门