Python高级笔记(八)with、上下文管理器
2024-08-26 08:50:50
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")
最新文章
- Bookshop(一)数据库连接
- github:如何获取项目源代码
- ThinkPHP 关于namespace的事儿
- 非常全面的讲解Hosts文件
- Period(KMP,循环节问题)
- 上传文件时 ContentType 浏览器差异
- 如何导出sqlserver中的表数据,sqlserver2008
- TCP连接状态详解及TIME_WAIT过多的解决方法
- java中对于JSON 的处理 fastjson gson 系统自带的JSON 的选择
- mabatis传入参数
- Windows权限提升基础知识和命令
- 移动APP测试方法总结
- tp5.0与mysql存储过程
- 基于AT89C51单片机烟雾传感器
- IIS Express
- python自学——文件打开
- centos7 + mysql5.7 tar包解压安装
- HTTP 状态信息
- 面向对象中的@classonlymethod 与 @classmethod的区别
- March 12 2017 Week 11 Sunday
热门文章
- 启动Vue项目,提示:Cannot find module 'webpack/bin/config-yargs'
- GITHUB下载源码
- python - 登陆验证的滑块接口
- Vue基础入门笔记
- Phoenix 简单介绍
- lixuxmint系统定制与配置(5)-效率配置
- (30)打鸡儿教你Vue.js
- 《挑战30天C++入门极限》C++的iostream标准库介绍(2)
- Java 合并PDF文件
- [CF 718C] Sasha and Array