2 回答
TA贡献1854条经验 获得超8个赞
确保您已导入该time模块。
在
__init__()类的函数中,将 的值time.time()放入变量中,例如self.spawned_time.在你的类中创建一个名为
can_destroy(). 该函数的代码如下:return time.time() >= self.spawned_time + <INSERT TIME THE CLASS WILL BE ALIVE>
完整代码:
import time
class MyClass:
def __init__(self):
self.spawned_time = time.time()
def can_destroy(self):
return time.time() > self.spawned_time + 6 # replace '6' with the seconds the class will exist for
my_instance = MyClass()
while True:
if my_instance.can_destroy():
# destroy your instance here
TA贡献1847条经验 获得超11个赞
我想这已经是两个问题了——
1)如何“杀死”一个类实例/对象?
这已经在这里很好地涵盖了: Python: how to "kill" a class instance/object?
2)如何制作过期功能。
您可能会查看 python 模块“expiringdict”——但还有许多其他具有过期功能的缓存实现。一开始,你可以看这里:https ://github.com/mailgun/expiringdict
我没有设法在评论中格式化你的第二个问题 -
我不知道创建时间与创建的实例一起存储,所以你需要自己做:
# STDLIB Imports
import time
Class Circle(object):
def __init__(self, diameter, x_coordinate, y_coordinate):
self.creation_time = time.time()
...
my_circle = Circle(1,0,0)
time.sleep(1)
print('creation time: {}'.format(my_circle.creation_time))
age = time.time() - my_circle.creation_time
print('age: {}'.format(age))
添加回答
举报
