装饰器的@是一个语法糖,调用被装饰的函数时相当于以下等式关系

装饰器不带参数:func() = 装饰器名(func)()

装饰器带参数:func() = time_count(‘参数’)(func)()


函数实现装饰器:

from functools import wraps
def time_count(参数):
    def test(fun):
        @wraps(fun)
        def wrapper(*args, **kwargs):
            print('装饰成功')
            return fun(*args, **kwargs)
        return wrapper
    return test

类实现装饰器:

def Test(param):
    class T:
        def __init__(self, fun):
            self._fun = fun

        def __call__(self, *args, **kwargs):
            print('装饰成功%s' % param)
            return self._fun(*args, **kwargs)
    return T

装饰类的装饰器:

def set_age(cls):
    setattr(cls, 'age', 18)
    return cls

@set_age
class Person:
    def __init__(self, name):
        self.name = name


aa = Person('aa')
print(aa.age)
> 18

参考 多层装饰器的调用及执行顺序