获取python中类对象的生命周期

时间:2017-08-26 12:01:39

标签: python python-3.x class time

我正在尝试实现这样的类:

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()这样的函数?

2 个答案:

答案 0 :(得分: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 :(得分: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