跟踪上次访问python对象的最优雅方法是什么?

Thi*_*yen 5 python tracking class object

我有一个python中的对象列表,我会定期检查并销毁其中的一些 - 最近没有访问过的那些(即没有调用方法).

我可以保持最后一次访问并在每个方法中更新它,但有没有更优雅的方法来实现这一点?

mhy*_*itz 6

正如@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指出的那样添加.