上下文管理,装饰一个函数

    xiaoxiao2024-11-21  3

    例:

    import datetime import time from functools import wraps,update_wrapper def logger3(duration=3): def _logger3(fn): @wraps(fn) def inner(*args,**kwargs): start = datetime.datetime.now() ret = fn(*args,**kwargs) delta = (datetime.datetime.now() - start).total_seconds() if delta > duration: print(fn.__name__,'{:.4f}'.format(delta) ) else: print('good') return ret return inner return _logger3 @logger3(0.1) 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.fn def __exit__(self, exc_type, exc_val, exc_tb): self.delta = (datetime.datetime.now() - self.start).total_seconds() print(self.delta,'111111111111111111') with Timeit(add3) as f: #with语句把enter的返回值赋给f,所以enter的返回值尤为重要 add3(3,4) #想实现f(3,4)? 怎么办? add3(3,4)
    最新回复(0)