zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python上下文管理器

Python 管理器 上下文
2023-06-13 09:15:31 时间

# 什么是上下文管理器

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

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

# 经典open案例

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

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

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

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

# 自定义上下文管理器

# 类实现

进入上下文时,调用__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
释放资源

# 方法实现

使用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