正如@Marcelo Cantos指出的那样,使用装饰器来处理你想要用时间戳功能包装的方法.
考虑这个例子:
from datetime import datetime
import time
import functools
def t_access(method):
@functools.wraps(method)
def wrapper(self):
self.timestamp = datetime.now()
method(self)
return wrapper
class Foo(object):
@t_access
def bar(self):
print "method bar() called"
f = Foo()
f.bar()
print f.timestamp
time.sleep(5)
f.bar()
print f.timestamp
Run Code Online (Sandbox Code Playgroud)
编辑:functools.wraps正如@Peter Milley指出的那样添加.