我在模块中有一个读取功能。
如果我同时执行该功能,我需要给它加上时间戳。
我该怎么做呢?
我将提供一种稍微不同的方法:
import time
def timestampit(func):
def decorate(*args, **kwargs):
decorate.timestamp = time.time()
return func(*args, **kwargs)
return decorate
@timestampit
def hello():
print 'hello'
hello()
print hello.timestamp
time.sleep(1)
hello()
print hello.timestamp
与 Swaroop 示例的不同之处在于:
#!/usr/bin/env python
import datetime
def timestampit(func):
def decorate(*args, **kwargs):
print datetime.datetime.now()
return func(*args, **kwargs)
return decorate
@timestampit
def hello():
print 'hello'
hello()
# Output:
# $ python test.py
# 2009-01-09 11:50:48.704584
# hello
Terik Ziade 的一些示例 代码
(更精致的版本,使用 timeit 模块,可以在他最近出版的《Expert Python Programming》一书中找到)
如果你有兴趣,python wiki 上有大量关于装饰器的信息。