python 的with用途(清理资源和异常处理,同时代码精简)
2018-02-25 23:11
471 查看
参考如下博客。
https://www.cnblogs.com/DswCnblog/p/6126588.html
运行结果:
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用法以及utf8中文显示
- Python小技巧之——巧用with语句实现异常处理
- python - 异常处理及with语句
- 使用try-with-resource改进代码异常处理机制
- python 异常处理 笔记 以及with 的用法
- 精简自己20%的代码(异常的处理)
- Head First Python---------(一)第一章(初识Python__人人都爱列表)、第二章(共享你的代码__函数模块)、第三章(文件与异常__处理错误)
- asp.net MVC 过滤器使用案例:统一处理异常顺道精简代码
- MVC过滤器使用案例:统一处理异常顺道精简代码
- MVC过滤器使用案例:统一处理异常顺道精简代码
- python异常处理示例代码
- Python 中的Selenium异常处理实例代码
- asp.net MVC 过滤器使用案例:统一处理异常顺道精简代码
- python异常处理救命代码
- MVC过滤器使用案例:统一处理异常顺道精简代码
- MVC过滤器使用案例:统一处理异常顺道精简代码
- MVC过滤器使用案例:统一处理异常顺道精简代码
- Python代码实现Java本地化资源字符串的检查,防止出现空指针异常
- python 对异常的处理(try...finally...和with 方法)- 千月的python linux 系统管理指南学习笔记(15)
- Python异常处理