1. # 你想在函数上添加一个包装器,增加额外的操作处理 (比如日志、计时等)。
    2. import time
    3. from functools import wraps
    4. def timethis(func):
    5. @wraps(func)
    6. def wrapper(*args, **kwargs):
    7. start = time.time()
    8. result = func(*args, **kwargs)
    9. end = time.time()
    10. print(func.__name__, end - start)
    11. return result
    12. return wrapper
    13. @timethis
    14. def countdown(n: int) -> None:
    15. '''
    16. Count down
    17. '''
    18. while n > 0:
    19. n -= 1
    20. countdown(100000)
    21. print(countdown.__name__)
    22. print(countdown.__doc__)
    23. print(countdown.__annotations__)
    24. print(countdown.__dict__)
    25. countdown.__wrapped__(10) # @wraps 有一个重要特征是它能让你通过属性 __wrapped__ 直接访问被包装函数。
    26. from inspect import signature
    27. print(signature(countdown)) # __wrapped__ 属性还能让被装饰函数正确暴露底层的参数签名信息。
    1. countdown 0.015611648559570312
    2. countdown
    3. Count down
    4. {'n': <class 'int'>, 'return': None}
    5. {'__wrapped__': <function countdown at 0x0000021E7DF952F0>}
    6. (n: int) -> None