2017-08-26 68 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