2 回答

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
確保您已導(dǎo)入該time
模塊。
在
__init__()
類的函數(shù)中,將 的值time.time()
放入變量中,例如self.spawned_time
.在你的類中創(chuàng)建一個(gè)名為
can_destroy()
. 該函數(shù)的代碼如下: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貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
我想這已經(jīng)是兩個(gè)問題了——
1)如何“殺死”一個(gè)類實(shí)例/對(duì)象?
這已經(jīng)在這里很好地涵蓋了: Python: how to "kill" a class instance/object?
2)如何制作過期功能。
您可能會(huì)查看 python 模塊“expiringdict”——但還有許多其他具有過期功能的緩存實(shí)現(xiàn)。一開始,你可以看這里:https ://github.com/mailgun/expiringdict
我沒有設(shè)法在評(píng)論中格式化你的第二個(gè)問題 -
我不知道創(chuàng)建時(shí)間與創(chuàng)建的實(shí)例一起存儲(chǔ),所以你需要自己做:
# 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))
添加回答
舉報(bào)