1 由来
装饰器也叫包装器(Wrapper),是Python对函数的一种包装。
因为python中“一切皆对象”,函数也是一个对象,可以赋值给变量:
def foo():
print('This is foo() method.')
f = foo
print(f.__name__)
f()
执行结果为:
foo
This is foo() method.
如果需要增强foo()
函数功能,又不想修改其定义,则可以通过装饰器来实现。
2 装饰器
本质上,decorator接受函数作为参数,就是一个返回函数的高阶函数。
def decor(fun):
def wrapper(*args, **kwargs):
print('wrapper function')
return fun(*args, **kwargs)
return wrapper
@decor
def haha(a , b):
c = a + b
print('haha', c)
def hehe(a, b):
c = a + b
print('hehe', c)
haha(2,3) # 等价于 decor(hehe)(2, 3)