2 回答

TA貢獻1854條經驗 獲得超8個贊
確保您已導入該time
模塊。
在
__init__()
類的函數中,將 的值time.time()
放入變量中,例如self.spawned_time
.在你的類中創(chuàng)建一個名為
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
我沒有設法在評論中格式化你的第二個問題 -
我不知道創(chuàng)建時間與創(chuàng)建的實例一起存儲,所以你需要自己做:
# 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))
添加回答
舉報