目录
例子1
被装饰的函数带有参数
例子1
用来说明代码运行逻辑
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(arg1, arg2):
print("I got args! Look:", arg1, arg2)
function_to_decorate(arg1, arg2)
return a_wrapper_accepting_arguments
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
print("My name is", first_name, last_name)
print_full_name("Peter", "Venkman")
I got args! Look: Peter Venkman
My name is Peter Venkman
被装饰的函数 print_full_name 有两个参数传进去,头上装饰器 a_decorator_passing_arguments ,它的参数 funciton_to_decorate 代表函数 print_full_name,表示把被装饰的函数传进去;
a_wrapper_accepting_arguments 才是装饰函数,agr1,agr2 代表被装饰函数的参数 "Peter", "Venkman";
等价写法,也是比较常见的写法,输出一样:
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(*args,**kwargs):
print("I got args! Look:", *args)
function_to_decorate(*args)
return a_wrapper_accepting_arguments
# 当你调用装饰器返回的函数式,你就在调用wrapper,而给wrapper的
# 参数传递将会让它把参数传递给要装饰的函数
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
print("My name is", first_name, last_name)
print_full_name("Peter", "Venkman")
例子2:
*args, **kwargs 都传入参数:
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
# The wrapper accepts any arguments
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
print("Do I have args?:")
print(args)
print(kwargs)
return function_to_decorate(*args, **kwargs)
return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus):
print("Do %s, %s and %s like platypus? %s" % (a, b, c, platypus))
function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!")
Do I have args?:
('Bill', 'Linus', 'Steve')
{'platypus': 'Indeed!'}
Do Bill, Linus and Steve like platypus? Indeed!
被装饰的函数没有参数
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
# The wrapper accepts any arguments
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
print("Do I have args?:")
print(args)
print(kwargs)
function_to_decorate(*args, **kwargs)
return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
print("Python is cool, no argument here.")
function_with_no_argument()
Do I have args?:
()
{}
Python is cool, no argument here.
因为被装饰的函数 function_with_no_argument 没有参数,所以 args,kwargs 为空
装饰函数带参数
def param(test=None):
def wrapper(func):
def factor_fun(*args,**kwargs):
if test:
print(test,'装饰函数有参数')
else:
print(test,'装饰函数 no 参数')
print(args,kwargs)
return func(*args,**kwargs)
return factor_fun
return wrapper
@param('test')
def zjk(*args,**kwargs):
print(args,kwargs)
zjk('1','2',name='zjk')
test 装饰函数有参数
('1', '2') {'name': 'zjk'}
('1', '2') {'name': 'zjk'}
以上代码装饰函数带有参数,可以看到装饰函数有两个闭包;
def param(test=None): 代表装饰函数,test 参数代表装饰函数自己的值
def wrapper(func): 代表被装饰函数在这里接收,fun 代表传进来的被装饰函数
def factor_fun(*args,**kwargs): 装饰函数真正的逻辑
所以一般装饰函数带有参数传入,一般都是三个 def 嵌套