猿问

删除一段时间后创建的类的实例

我正在尝试实现一个函数,该函数将删除在一段时间后创建的类的实例,但是我似乎无法实现这样的方法已尝试查找从创建类实例到目前的时间,但这似乎不太顺利,任何建议都会很有帮助!



郎朗坤
浏览 405回答 2
2回答

哔哔one

确保您已导入该time模块。在__init__()类的函数中,将 的值time.time()放入变量中,例如self.spawned_time.在你的类中创建一个名为can_destroy().&nbsp;该函数的代码如下:return time.time() >= self.spawned_time + <INSERT TIME THE CLASS WILL BE ALIVE>完整代码:import timeclass MyClass:&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.spawned_time = time.time()&nbsp; &nbsp; def can_destroy(self):&nbsp; &nbsp; &nbsp; &nbsp; return time.time() > self.spawned_time + 6&nbsp; # replace '6' with the seconds the class will exist formy_instance = MyClass()while True:&nbsp; &nbsp; if my_instance.can_destroy():&nbsp; &nbsp; &nbsp; &nbsp; # destroy your instance here

回首忆惘然

我想这已经是两个问题了——1)如何“杀死”一个类实例/对象?这已经在这里很好地涵盖了:&nbsp;Python: how to "kill" a class instance/object?2)如何制作过期功能。您可能会查看 python 模块“expiringdict”——但还有许多其他具有过期功能的缓存实现。一开始,你可以看这里:https ://github.com/mailgun/expiringdict我没有设法在评论中格式化你的第二个问题 -我不知道创建时间与创建的实例一起存储,所以你需要自己做:# STDLIB Importsimport timeClass Circle(object):&nbsp; &nbsp; def __init__(self, diameter, x_coordinate, y_coordinate):&nbsp; &nbsp; &nbsp; &nbsp; self.creation_time = time.time()&nbsp; &nbsp; &nbsp; &nbsp; ...my_circle = Circle(1,0,0)time.sleep(1)print('creation time: {}'.format(my_circle.creation_time))age = time.time() - my_circle.creation_timeprint('age: {}'.format(age))
随时随地看视频慕课网APP

相关分类

Python
我要回答