总结
定义了__enter__和__exit__方法的类,被称做上下文管理器
常规文件操作
f = open("mydata.txt", 'w')
f.write("hello")
f.close()
上下文管理器的文件操作例子
with open("mydata.txt", 'a') as f:
f.write("python")
常规计时器例子
import time
start = time.perf_counter()
time.sleep(random.randint(0, 1))
end = time.perf_counter()
print(f"执行了{end - start}秒")
例子
import time
class MyTimer:
def __int__(self):
self.elapse = 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.elapse = self.end - self.start
return self.elapse
with MyTimer() as timer:
time.sleep(random.uniform(0, 1))
print(f"耗时:{timer.elapse}")
- 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
- 28