【文件属性】:
文件名称:使用装饰器扩充类的功能-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2021-06-10 05:19:49
python cookbook 第3版 高清 中文完整版
9.12 使用装饰器扩充类的功能
问题
你想通过反省或者重写类定义的某部分来修改它的行为,但是你又不希望使用继承或元类
的方式。
解决方案
这种情况可能是类装饰器 好的使用场景了。例如,下面是一个重写了特殊方法
__getattribute__ 的类装饰器, 可以打印日志:
def log_getattribute(cls):
# Get the original implementation
orig_getattribute = cls.__getattribute__
# Make a new definition
def new_getattribute(self, name):
print('getting:', name)
return orig_getattribute(self, name)
# Attach to the class and return
cls.__getattribute__ = new_getattribute
return cls
# Example use
@log_getattribute
class A:
def __init__(self,x):
self.x = x
def spam(self):
pass
下面是使用效果:
>>> a = A(42)
>>> a.x
getting: x
42
>>> a.spam()
getting: spam
>>>