python实现作用在类上的装饰器

除了可以用在方法上,其实python的装饰器也可以作用于类上,在不改变类的情况下,给类增加一些额外的功能.

# 下面是一个重写了特殊方法 __getattribute__ 的类装饰器,可以打印日志:
def log_getattribute(cls):
    origin_getattribute=cls.__getattribute__

    def new_getattribute(self,name):
        print('greeting:',name)
        return origin_getattribute(self,name)

    cls.__getattribute__=new_getattribute
    return cls 

#应用
@log_getattribute
class A:
    def __init__(self,x):
        self.x=x

    def spam(self):
        pass

if __name__=='__main__':
    a=A('x')
    print(a.x)
    print(a.spam())

#输出
greeting: x
x
greeting: spam
None

 

posted @ 2020-06-16 15:53  Mars.wang  阅读(908)  评论(0编辑  收藏  举报