with as 呢,就是个python控制流语句,像 if ,while。
with as 语句的结构:
with expression [as variable]:
with-block
with expresion as variable的执行过程是
- 首先执行_enter_函数,它的返回值会赋给as后面的variable,想让它返回什么就返回什么,只要你知道怎么处理就可以了,如果不写as variable,返回值会被忽略。
- 然后,开始执行with-block中的语句,不论成功失败(比如发生异常、错误,设置sys.exit()),在with-block执行完成后,会执行_exit_函数。
等价于:
try:
执行 _enter_的内容
执行 with_block.
finally:
执行 _exit_内容
附:try finally功能演示例子 (顺序执行try内语句,如果有错跳进except报错语句执行,随后直接进入finally。不管是否有错,都要执行finally)
try:
a=1/2
print (a)
b = 1 / 0 # an abnormal number/variable
print (b)
c = 2 / 1 # a normal number/variable
print (c)
except NameError:
print("ops")
except ZeroDivisionError:
print("wrong math")
except:
print("error")
#else:
# print("no error")
finally:
print("end")
例子1(无报错):
class Sample:
def __enter__(self):
print "In __enter__()"
return "Foo"
def __exit__(self, type, value, trace):
print "In __exit__()"
def get_sample():
return Sample()
with get_sample() as sample:
print "sample:", sample
执行步骤:
调用get_sample()函数,返回Sample()类;
执行Sample类中的enter()方法,打印”In__enter_()”字符串,并将字符串“Foo”赋值给as后面的sample变量;
- 执行with-block码块,即打印”sample: %s”字符串,结果为”sample: Foo”
- 执行with-block码块结束,返回Sample()类,执行类方法exit()。因为在执行with-block码块时并没有错误返回,所以type,value,trace这三个arguments都没有值。直接打印 print “In__exit__()”
结果:
In __enter__()
sample: Foo
In __exit__()
例子2(有报错):
class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print "type:", type
print "value:", value
print "trace:", trace
def do_something(self):
bar = 1/0
return bar + 10
with Sample() as sample:
sample.do_something()
结果:
type: <class 'ZeroDivisionError'>
value: division by zero
trace: <traceback object at 0x000000000EC6F7C8>
Traceback (most recent call last):
File "<ipython-input-16-1f63b4f99f4d>", line 13, in <module>
sample.do_something()
File "<ipython-input-16-1f63b4f99f4d>", line 9, in do_something
bar = 1/0
ZeroDivisionError: division by zero