1. 上下文管理器

__enter__()方法返回资源对象,__exit__()方法处理一些清除资源

如:系统资源:文件、数据库链接、Socket等这些资源执行完业务逻辑之后,必须要关闭资源

#!/usr/bin/python3
#-*- coding:utf- -*- class File(object): def __init__(self, filename, mode):
self.filename = filename
self.mode = mode def __enter__(self):
print("entering....")
self.f = open(self.filename, self.mode)
return self.f def __exit__(self, *args):
print("will exit")
self.f.close() with File("out.txt", 'w') as f:
print("writing....")
f.write('hello, python')
entering....
writing....
will exit

2. 使用 @contextmanager

from contextlib import contextmanager

@contextmanager
def my_open(path, mode):
f = open(path, mode)
yield f
f.close() with my_open('out.txt', 'w') as f:
f.write("hello, test")

最新文章

  1. Bookshop(一)数据库连接
  2. github:如何获取项目源代码
  3. ThinkPHP 关于namespace的事儿
  4. 非常全面的讲解Hosts文件
  5. Period(KMP,循环节问题)
  6. 上传文件时 ContentType 浏览器差异
  7. 如何导出sqlserver中的表数据,sqlserver2008
  8. TCP连接状态详解及TIME_WAIT过多的解决方法
  9. java中对于JSON 的处理 fastjson gson 系统自带的JSON 的选择
  10. mabatis传入参数
  11. Windows权限提升基础知识和命令
  12. 移动APP测试方法总结
  13. tp5.0与mysql存储过程
  14. 基于AT89C51单片机烟雾传感器
  15. IIS Express
  16. python自学——文件打开
  17. centos7 + mysql5.7 tar包解压安装
  18. HTTP 状态信息
  19. 面向对象中的@classonlymethod 与 @classmethod的区别
  20. March 12 2017 Week 11 Sunday

热门文章

  1. 启动Vue项目,提示:Cannot find module 'webpack/bin/config-yargs'
  2. GITHUB下载源码
  3. python - 登陆验证的滑块接口
  4. Vue基础入门笔记
  5. Phoenix 简单介绍
  6. lixuxmint系统定制与配置(5)-效率配置
  7. (30)打鸡儿教你Vue.js
  8. 《挑战30天C++入门极限》C++的iostream标准库介绍(2)
  9. Java 合并PDF文件
  10. [CF 718C] Sasha and Array