2017-08-26 66 views
2

我想實現這樣一個類的壽命:獲取Python中的類對象

class A: 

    # some functions.. 

    def foo(self, ...) 
     # if self has been instantiated for less than 1 minute then return 
     # otherwise continue with foo's code 

,我想知道,有沒有實現像foo()功能的方法嗎?

+0

不能讓你用'的意思是如果自己已經被實例化了不到1個minute' – Bijoy

回答

4

一個簡單的方法是將存儲創建的實例屬性的時間戳:

from datetime import datetime, timedelta 

class A: 
    def __init__(self): 
     self._time_created = datetime.now() 

    def foo(self): 
     if datetime.now() - self._time_created < timedelta(minutes=1): 
      return None 
     # do the stuff you want to happen after one minute here, e.g. 
     return 1 

a = A() 
while True: 
    if a.foo() is not None: 
     break 
1

你可以這樣來做:

from datetime import datetime 
from time import sleep 

class A: 

    # some functions.. 
    def __init__(self): 
     self._starttime = datetime.now() 

    def foo(self): 
     # if self has been instantiated for less than 1 minute then return 
     # otherwise continue with foo's code 
     if (datetime.now() - self._starttime).total_seconds() < 60: 
      print "Instantiated less than a minute ago, returning." 
      return 
     # foo code 
     print "Instantiated more than a minute ago, going on" 

變量用來存儲調用時間的對象構造函數,然後用於區分函數行爲。

如果運行

a = A() 
sleep(3) 
a.foo() 
sleep(61) 
a.foo() 

$ python test.py 
Instantiated less than a minute ago, returning. 
Instantiated more than a minute ago, going on