您的位置:首页 > 编程语言 > Python开发

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

2018-02-25 23:11 471 查看
参考如下博客。
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()


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: