浅笑の博客

我们的征途是星辰大海


  • 首页

  • 标签29

  • 分类6

  • 归档47

  • 留言板

  • 搜索

python——with语句和contextlib模块

发表于 2019-07-29 分类于 Python Valine: 本文字数: 1.4k

with语句

创建上下文管理实际就是创建一个类,添加enter和exit方法。下面我们来实现open的上下文管理功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class OpenContext(object):

def __init__(self, filename, mode):
self.fp = open(filename, mode)

def __enter__(self):
return self.fp

def __exit__(self, exc_type, exc_val, exc_tb):
self.fp.close()


with OpenContext('/tmp/a.txt', 'a') as file_obj:
file_obj.write("hello 6666")

contextlib模块

上面我们自定义上下文管理器确实很方便,但是Python标准库还提供了更加易用的上下文管理器工具模块contextlib,它是通过生成器实现的,我们不需要再创建类以及enter和exit这两个特俗的方法:

1
2
3
4
5
6
7
8
9
10
11
12
from contextlib import contextmanager

@contextmanager
def make_open_context(filename, mode):
fp = open(filename, mode)
try:
yield fp
finally:
fp.close()

with make_open_context('/tmp/a.txt', 'a') as file_obj:
file_obj.write("hello 666")

在上文中,yield关键词把上下文分割成两部分:yield之前就是init中的代码块;yield之后其实就是exit中的代码块,yield生成的值会绑定到with语句as子句中的变量,例如在上面的例子中,yield生成的值是文件句柄对象fp,在下面的with语句中,会将fp和file_obj绑定到一起,也就是说file_obj此时就是一个文件句柄对象,那么它就可以操作文件了,因此就可以调用file_obj.write(“hello 666”),另外要注意的是如果yield没有生成值,那么在with语句中就不需要写as子句了

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
# _*_ coding:utf-8 _*_

from contextlib import contextmanager

@contextmanager
def book_mark():
print('《', end="")
yield
print('》', end="")

with book_mark():
# 核心代码
print('且将生活一饮而尽', end="")

这样在打印书名时,通过上下文管理器,会自动加上书名号

Python库
Hexo使用数学公式
Python——argparse模块
Zheng Yujie

Zheng Yujie

C++/Python/深度学习
47 日志
6 分类
29 标签
目录
  1. 1. with语句
  2. 2. contextlib模块
  3. 3. 案例
© 2019 Zheng Yujie | 全站共199k字
浙ICP备 - 19035016号
0%