你可以这样来做:
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