你可以這樣來做:
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
不能讓你用'的意思是如果自己已經被實例化了不到1個minute' – Bijoy