自动过期变量
问题内容:
如何在python中实现自动过期的变量?例如,让程序运行一小时。我想实现一个由6个变量组成的数组,数组中的每个变量都会在10分钟后自动删除。1小时后,数组中将没有任何变量。
问题答案:
您可以创建一个后台进程,以检查它经过了多少时间,然后删除正确的项…或者如果您想创建一个列表列表的子类,并在一定时间后将其删除,则可以执行相同的操作,只需调用它即可在
初始化
def __init__(self, time):
#run subprocess to chek_espired elements
编辑:
我写了一个例子,但是可以做得更好!
class MyList(list):
def __init__(self,elems, expires_time):
list.__init__(self, elems)
self.created = time.time()
self.expires_time = expires_time
def __getitem__(self, index):
t = time.time()
print t - self.created
if t - self.created > self.expires_time:
self.created += self.expires_time
self.pop(index)
self.__getitem__(index)
return list.__getitem__(self, index)
ps当然,如果程序尝试从空列表中获取索引,则很容易引发人为错误