with as 語句
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()
在Sample()調(diào)用時(shí)進(jìn)入enter()函數(shù)聋涨,返回對(duì)象,然后調(diào)用dosth冤今,產(chǎn)生錯(cuò)誤時(shí)調(diào)用exit()打印錯(cuò)誤信息