1. # 你想给类方法或静态方法提供装饰器
    2. # 给类或静态方法提供装饰器是很简单的,不过要确保装饰器在 @classmethod 或 @staticmethod 之前。例如:
    3. import time
    4. from functools import wraps
    5. def timethis(func):
    6. @wraps(func)
    7. def wrapper(*args, **kwargs):
    8. start = time.time()
    9. r = func(*args, **kwargs)
    10. end = time.time()
    11. print(end - start)
    12. return r
    13. return wrapper
    14. class Spam:
    15. @timethis
    16. def instance_method(self, n):
    17. print(self, n)
    18. while n > 0:
    19. n -= 1
    20. @classmethod
    21. @timethis
    22. def class_method(cls, n):
    23. print(cls, n)
    24. while n > 0:
    25. n -= 1
    26. @staticmethod
    27. @timethis
    28. def static_method(n):
    29. print(n)
    30. while n > 0:
    31. n -= 1
    32. s = Spam()
    33. s.instance_method(10000000)
    34. Spam.class_method(10000000)
    35. Spam.static_method(10000000)
    1. <__main__.Spam object at 0x0000014F7C5C9B70> 10000000
    2. 0.844519853591919
    3. <class '__main__.Spam'> 10000000
    4. 0.898040771484375
    5. 10000000
    6. 0.8993453979492188