目前我知道的装饰器有两种,一种是类(型)装饰器,另一种是函数(型)装饰器。
不带参数的装饰器
def decorator(func): def wrapper(*args,**kwargs): #装饰内容 res = func(*args,**kwargs) #装饰内容 return res return wrapper带参数的装饰器(多了个层级)
def decorator(auth_type): def deco(func): def wrapper(*args,**kwargs): #装饰内容 #使用auth_type变量 res = func(*args,**kwargs) #装饰内容 return res return wrapper return deco装饰器实为从外向里运行,其中需要考虑变量作用域,函数及变量。
类(型)装饰器
class Foo(): def __init__(self,func): self._func = func def __call__(self): #修饰内容 res = self.func() #修饰内容 return res装饰器的使用方法为在函数前一行加上@ [装饰器名]
def decorator(auth_type): def deco(func): def wrapper(*args,**kwargs): #装饰内容 #使用auth_type变量 res = func(*args,**kwargs) #装饰内容 return res return wrapper return deco @decorator("你想填啥就填啥") def hello(name): print("Hello",name)装饰器在很多语言中都有,在各种生产环境的调整中都起着不可或缺的作用。
参照知乎,https://www.zhihu.com/question/26930016
顺带一提py3中不存在被装饰函数的元数据备顶替情况。可以使用 .__doc__,.__name__获得原函数元数据。
转载于:https://www.cnblogs.com/the-moon-so-beautiful/p/8436950.html