装饰器之类装饰器
一、类中的方法实现装饰器
类当中的方法和普通方法一样,使用方法一样,只有对象进行调用的时候,第一个参数会默认吧对象实例传入,然后隐匿
这个相当于__call__和__new__一类的东西吧
def godme(fun): def __godme(self,message): print('before') fun(self,message) print('after') return __godme class Person: def show(self,message): print(message) @godme def say(self,message): print(message) person = Person() person.say('happy')
打印结果: ''' before happy after "
二、类上实现装饰器1
def godme(fun): def __godme(cls,*args,**kwargs): print('before') fun(cls,*args,**kwargs) print('after') return __godme
@godme class Person: def __new__(cls, *args, **kwargs): print('__new__') 打印结果: before __new__ after
三、类上实现装饰器2
class tracer(object): def __init__(self, func): self.calls = 0 self.func = func def __call__(self, *args, **kwargs): self.calls += 1 print("call %s to %s" % (self.calls, self.func.__name__)) self.func(*args, **kwargs) @tracer def spam(a, b, c): print(a, b, c) if __name__ == '__main__': spam(1, 2, 3) spam("a", "b", "c") spam(4, 5, 6) 打印结果: call 1 to spam 1 2 3 call 2 to spam a b c call 3 to spam 4 5 6
https://www.cnblogs.com/WiseAdministrator/