上下文管理,调用call函数
例:
def add3(x,y):
time.sleep(1)
return x + y
class Timeit:
def __init__(self,fn):
self.fn = fn
def __enter__(self):
self.start = datetime.datetime.now()
return self #1,返回值是self 说明返回了实例给f,f(3,4)需要call方法
def __exit__(self, exc_type, exc_val, exc_tb):
self.delta = (datetime.datetime.now() - self.start).total_seconds()
print(self.delta,'111111111111111111')
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs) #2,call方法返回函数self存的函数self.fn
#self = Timeit(add3)
with Timeit(add3) as f: #3,f拿到函数,直接调用
f(3,4)