1. # 你想通过反省或者重写类定义的某部分来修改它的行为,但是你又不希望使用继承或元类的方式。
    2. # 这种情况可能是类装饰器最好的使用场景了。例如,下面是一个重写了特殊方法 __getattribute__ 的类装饰器, 可以打印日志:
    3. def log_getattribute(cls):
    4. orig_getattribute = cls.__getattribute__
    5. def new_getattribute(self, name):
    6. print('getting:', name)
    7. return orig_getattribute(self, name)
    8. cls.__getattribute__ = new_getattribute
    9. return cls
    10. @log_getattribute
    11. class A:
    12. def __init__(self, x):
    13. self.x = x
    14. def spam(self):
    15. pass
    16. a = A(42)
    17. print(a.x)
    18. a.spam()
    1. getting: x
    2. 42
    3. getting: spam