郑文峰的博客 郑文峰的博客
首页
  • python之路
  • go之路
  • 其他
  • redis
  • mysql
  • docker
  • k8s
读书破万卷
周刊
关于
  • 导航 (opens new window)
  • 代码片段 (opens new window)
  • 收藏
  • 友链
  • 外部页面

    • 开往 (opens new window)
  • 索引

    • 分类
    • 标签
    • 归档
GitHub (opens new window)

zhengwenfeng

穷则变,变则通,通则久
首页
  • python之路
  • go之路
  • 其他
  • redis
  • mysql
  • docker
  • k8s
读书破万卷
周刊
关于
  • 导航 (opens new window)
  • 代码片段 (opens new window)
  • 收藏
  • 友链
  • 外部页面

    • 开往 (opens new window)
  • 索引

    • 分类
    • 标签
    • 归档
GitHub (opens new window)
  • python

    • 基础

      • python迭代器与生成器
      • python元编程
      • python垃圾回收机制
      • python上下文管理器
        • 什么是上下文管理器
        • 经典open案例
        • 自定义上下文管理器
          • 类实现
          • 方法实现
      • python装饰器的使用方法
      • 使用python实现单例模式的三种方式
      • python中import原理
    • 第三方库

    • django

    • flask

    • tornado

    • 其他

  • go

  • 其他

  • 编程
  • python
  • 基础
zhengwenfeng
2022-08-10
目录

python上下文管理器

# 什么是上下文管理器

python中使用with来使用上下文管理器.

在使用某个资源时,可以对该资源进行初始化和资源的清理两个操作,在这两个操作之间边成为上下文。

# 经典open案例

对文件操作时,需要打开文件及关闭文件。然后在这之间进行文件的操作。

f = open("a.txt")
f.write("hello world")
f.close()
1
2
3

使用上下文管理器 打开文件后,得到文件描述符,在with代码块中对f进行操作,结束时,会自动的进行关闭操作.

with open("a.txt") as f:
    f.write("hello world")
1
2

# 自定义上下文管理器

# 类实现

进入上下文时,调用__enter__方法进行初始化,退出时,调用__exit__退出。


class A:
def __enter__(self):
    print("进入")

def __exit__(self, exc_type, exc_val, exc_tb):
    print("释放资源")

with A() as f:
    print("hello")
    print("world")
   
output: 
进入
hello
world
释放资源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 方法实现

使用contextlib.contextmanager 对方法实现上下文管理器. 使用生成器完成。


import contextlib

@contextlib.contextmanager
def test(a):
    print("open..")
    yield a
    print("close")
    
with test(2) as f:
    print(f)

output:
open..
2
close
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#python
上次更新: 2023/01/15, 15:47:48
python垃圾回收机制
python装饰器的使用方法

← python垃圾回收机制 python装饰器的使用方法→

最近更新
01
django rest_framework 分页
03-20
02
学习周刊-第03期-第09周
03-03
03
学习周刊-第02期-第08周
02-24
更多文章>
Theme by Vdoing | Copyright © 2022-2023 zhengwenfeng | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式