有一个函数f1,在不改变函数f1内部代码的情况,让其每次运行时都打印出及时的时间戳
实例:
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
@decorator # 语法糖
def f1():
print('This is a function')
f1() # 1569403332.0502675 \ This is a function
优势:没有改变调用方式
有一个或多个函数参数、关键字参数的装饰器的使用
实例:
import time
def decorator(func):
def wrapper(*args, **kw):
print(time.time())
func(*args, **kw)
return wrapper
@decorator
def f1(func_name):
print('This is ' + func_name)
@decorator
def f2(func_name1, func_name2):
print('This is ' + func_name1)
print('This is ' + func_name2)
@decorator
def f3(func_name1, func_name2, **kw):
print('This is ' + func_name1)
print('This is ' + func_name2)
print(kw)
f1('test') # 1569404249.6017482 \ This is test
f2('test2.1', 'test2.2') # 1569404249.6017482 \ This is test2.1 \ This is test2.2
f3('test3.1', 'test3.2', a=1, b=2, c='1,2,3') # 1569404981.3045993 \ This is test3.1 \ This is test3.2 \ {'a': 1, 'b': 2, 'c': '1,2,3'}