对没有参数传递的函数使用装饰器可以如下:
import time
def f1():
print('hello world')
def print_current_time(func):
print(time.time())
func()
print_current_time(f1)
假如f1
函数中有一个参数,再另一个函数f2
要传递两个参数:
def f1(func_name):
print('Hello world!' + func_name)
def f2(func_name1,func_name2):
print(func_name1+func_name2)
而定义的嵌套函数装饰器:
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
要知道:
这个定义的装饰器和时间相关的,和特定的函数相关的并没有任何意义。任何函数都可以使用它。
然而,f1
中需要传递一个参数,f2
要传递两个参数,要使得定义的装饰器对f1
和f2
有通用性,就有了可变参数列表*args
,
import time
def decorator(func):
def wrapper(*args):
print(time.time())
func(*args)
return wrapper
@decorator
def f1(func_name):
print('Hello world!' + func_name)
@decorator
def f2(func_name1,func_name2):
print(func_name1+func_name2)
f1('hello')
f2('he','llo')
------------------------------------------
输出:
1535900316.7922134
Hello world!hello
1535900316.7922134
hello
args
可变参数列表 支持不同个数的参数。
*args
,args
这个词汇是根据自身业务使用对应的词汇。