简单使用
def decorator(new_func): def inner(): print("+++") new_func() return inner @decorator def show(): print("BBB") show() #结果如下: +++ BBB
装饰器带有参数的函数
def decorator(func): def inner(num1,num2): print("计算结果如下:") func(num1,num2) return inner @decorator def sum(num1,num2): result=num1+num2 print(result) sum(2,3) #结果如下: 计算结果如下: 5
通用的装饰器
def decorator(func): def inner(*args, **kwargs): print("计算结果如下", end=" ") result=func(*args, **kwargs) return result return inner @decorator def sum(num1, num2, num3): result = num1 + num2 + num3 return result result = sum(1, 2,5) print(result) #结果如下: 计算结果如下 8
带有参数的装饰器
def get_decorator(char): def decorator(func): def inner(): print(char) func() return inner return decorator @get_decorator("aaaa") def show(): print("1111") show() #结果如下: aaaa 1111