我有一个 python 对象列表,我会定期检查并销毁其中的一些对象——那些最近没有被访问过的对象(即没有调用任何方法)。
我可以维护上次访问的时间并在每个方法中更新它,但是有没有更优雅的方法来实现这一点?
最佳答案
正如@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
编辑:添加了 functools.wraps
,正如@Peter Milley 所指出的。
关于python - 跟踪上次访问 python 对象的最优雅方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6241448/