5
Python 如何将上下文管理器中的段落执行多次?
source link: https://www.v2ex.com/t/814044
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
# 提前声明一个上下文管理器
class timer:
...
# 调用这个管理器时实现如下效果:
import timer
with timer(100):
x = 12 * 12
# 计算一百次 x=12*12 计算消耗的时间,等同于 for range(100)
10 条回复 • 2021-11-09 16:29:08 +08:00
jaredyam 8 小时 15 分钟前
个人认为怎么都会多此一举。class 上下文管理主要靠 with 的传参,__enter__、__exit__方法控制,你这真要真么搞也就是在__enter__里加个 for range 。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK