以装饰一个函数为例子, 打印出函数的开始执行时间。
常规方式实现:
import time
def printTime(func):
def wrapper(*args, **kwargs):
print(time.ctime())
return func(*args, **kwargs)
return wrapper
def printHello(name):
print('Hello', name)
if __name__ == '__main__':
printhello_plus = printTime(printHello)
printhello_plus('Sam')
输出:
Tue Nov 27 17:12:10 2018
Hello Sam
装饰器方式实现:
import time
def printTime(func):
def wrapper(*args, **kwargs):
print(time.ctime())
return func(*args, **kwargs)
return wrapper
@printTime
def printhello(name):
print('Hello', name)
if __name__ == '__main__':
printhello('Sam')
输出:
Tue Nov 27 17:21:13 2018
Hello Sam
网友评论