类装饰器在扩展类功能中的应用
在想要修改类的特定行为时,类装饰器可以提供一种方便的替代方案,无需继承或元类。例如,以下类装饰器重写了__getattribute__方法,在属性获取时打印日志信息:
def log_getattribute(cls):
orig_getattribute = cls.getattribute
def new_getattribute(self, name):
print('getting:', name)
return orig_getattribute(self, name)
cls.getattribute = new_getattribute
return cls
@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
4.84MB
文件大小:
评论区