上下文管理器
什么是上下文管理器
- context manager
- 是一个对象
- 定义了运行时的上下文
- 使用
with语句来执行
格式:
文件的读写
1 2 3 4 5 6 7 8
| fileObj = open("file.txt","w") fileObj.write("This is my file") fileObj.close()
with open("file.txt","w") as fileObj: fileObj.write("This is my file")
|
- 使用
with语句,会在代码块结束时,自动帮我们关闭文件,无需手动触发 close()方法
- 在
with语句,开始前会触发__enter__(self)
- 在
with语句结束后会触发__exit__(self, exc_type, exc_val, exc_tb)
as后面的对象 实际是在调用完__enter__后获取到的返回值
使用上下文管理器实现一个耗时计算函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| nums = [i for i in range(10000)] random.shuffle(nums) start = time.perf_counter() sorted(nums) end = time.perf_counter() elapsed = end - start print(elapsed)
class Timer: def __init__(self): self.elapsed = 0
def __enter__(self): self.start = time.perf_counter() return self
def __exit__(self, exc_type, exc_val, exc_tb): self.end = time.perf_counter() self.elapsed = self.end - self.start
with Timer() as timer: sorted(nums)
print(timer.elapsed)
|
更新: 2024-01-09 02:16:57
原文: https://www.yuque.com/zacharyblock/cx2om6/ofmfwtiq1h6wysmp
Author:
Zachary Block
Permalink:
http://blockzachary.cn/blog/4030205442/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE