class Time:
def __init__(self):
self.elapsed = elapsed
def __enter__(self):
self.start =time.pref_counter()
return self
def __exit__(self,exc_type, exc_val, exc_tb):
self.stop=time.pref_counter()
self.elapsed = self.stop - self.start
return elapsed
with Time() as timer:
for n in range(100):
print(i)
这里上下文管理器的with实际是先吧Time类里面的__enter__的返回值赋给timer,然后再去调用__exit__
with opon(file) as f:原理也是一样的
python上下文管理器
最新推荐文章于 2024-08-27 16:38:10 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)