python 的with用途(清理资源和异常处理,同时代码精简)

时间:2023-04-24 22:49:44

参考如下博客。

https://www.cnblogs.com/DswCnblog/p/6126588.html

#!/usr/bin/env python
# with_example02.py class Sample:
def __enter__(self):
print "go to enter():"
return self def __exit__(self, type, value, trace):
print "go to exit():"
print "type:", type
print "value:", value
print "trace:", trace def do_something(self):
print "go to do_something():"
bar = 1/0
return bar + 10 with Sample() as sample:
sample.do_something()

运行结果:

python 的with用途(清理资源和异常处理,同时代码精简)