def function1():
print('i am a funcation!')
def function1():
print('i am a function!')
print('function1 is running!')
def log(func):
print('%s is runnning!' % func.__name__)
return func
@log
def function1():
print('i am a function!')
function1()
>>>
function1 is runnning!
i am a function!
def log(func):
def _decoration():
print('%s is runnning!' % func.__name__)
func()
return _decoration
@log
def function1():
print('i am a function!')
function1()
>>>
function1 is runnning!
i am a function!
见上例装饰器
def log(func):
def _decoration(a, b):
print('%s is runnning!' % func.__name__)
func(a, b)
return _decoration
@log
def function1(a, b):
s = a + b
print('the result is %d' % s)
print('i am a function!')
function1(1, 2)
>>>
function1 is runnning!
the result is 3
i am a function!
def log(func):
def _decoration(*args, **kwargs):
print('%s is runnning!' % func.__name__)
func(*args, **kwargs)
return _decoration
@log
def function1(a, b):
s = a + b
print('the result is %d' % s)
print('i am a function!')
@log
def function2(a, b, c):
s = a + b - c
print('the result is %d' % s)
print('i am a function!')
function1(1, 2)
function2(1, 2, 3)
>>>
function1 is runnning!
the result is 3
i am a function!
function2 is runnning!
the result is 0
i am a function!
栗子如下:
def log(func):
def _decoration():
print('%s is runnning!' % func.__name__)
func()
return _decoration
@log
def function1():
print('i am a function!')
print(function1.__name__)
function1()
>>>
function1 is runnning!
i am a function!
_decoration
发现此处打印的不是function1的函数名.
使用上述代码的缺点就是原函数的信息不见了. 如: name, 参数列表等.
所以这里引入@functools.wraps
import functools
def log(func):
@functools.wraps(func)
def _decoration():
print('%s is runnning!' % func.__name__)
func()
return _decoration
@log
def function1():
print('i am a function!')
print(function1.__name__)
function1()
>>>
function1 is runnning!
i am a function!
function1
import functools
class Log(object):
def __call__(self, func):
@functools.wraps(func)
def _decoration():
print('%s is runnning!' % func.__name__)
func()
return _decoration
@Log()
def function1():
print('i am a function!')
print(function1.__name__)
function1()
>>>
function1 is runnning!
i am a function!
function1
多个类装饰一个函数时,调用时有一定的顺序 . 简单来说,就是装饰器调用顺序与@ 声明的顺序相反.
装饰器可以在不改变原函数功能的情况下,给原函数实现其他功能,同时,又能复用大量代码,减少冗余.
它常被用于有切面需求的场景, 如: 打印日志, 记录时间, 权限校验, 事务处理, 缓存等场景.