1,啥叫装饰器?
装饰器就是在Python中的类或者函数前面通过@访问的特殊方法,例如@staticmethod或@classmethod等。
2,有什么用?
对于一些函数在进入前或退出后具有相同的操作处理,或者对于某个函数在不改变该函数代码的前提下,为该函数添加额外的功能。
例如:函数进入和退出时记录操作日志信息,记录函数的调用次数,执行时间等。
3,定义方式:
4,自定义装饰器:
# (1)装饰器定义 def log(func): def wrapper(*arg, **kwargs): print "函数%s被调用了:" % func.__name__ return func(*arg, **kwargs) return wrapper @log # 等价于:test = log(test) def test(): print 100 test() print test.__name__ # 此时test等价log的内函数wrapper #------------输出---------- # 函数test被调用了: # 100 # wrapper #------------------------- # (2)希望test.__name__获取它自身的名字 import functools def log2(func): @functools.wraps(func) def wrapper(*arg, **kwargs): print "函数%s被调用了:" % func.__name__ return func(*arg, **kwargs) return wrapper @log # 等价于:test = log(test) def test(): print 100 test() print test.__name__ #------------输出---------- # 函数test被调用了: # 100 # test #------------------------- # (3)定义带参数的装饰器函数 import functools def log3(param1, param2): def decorator(func): @functools.wraps(func) def wrapper(*arg, **kwargs): print param1, param2 print "函数%s被调用了:" % func.__name__ return func(*arg, **kwargs) return wrapper return decorator @log3(1, 2) # 等价于:test = log(test) def test(): print 100 test() #------------输出---------- # 1 2 # 函数test被调用了: # 100 #-------------------------
5,wrapt定义装饰器:
wrapt 官网:http://wrapt.readthedocs.io/en/latest/quick-start.html
原文:https://www.cnblogs.com/lwp-boy/p/13586083.html