【问题标题】:Get the lifetime of a class object in python在python中获取类对象的生命周期
【发布时间】:2018-02-04 07:32:20
【问题描述】:

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

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() 这样的功能?

【问题讨论】:

  • 无法理解if self has been instantiated for less than 1 minute的意思

标签: python python-3.x class time


【解决方案1】:

一种简单的方法是将创建的时间戳存储为实例属性:

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

【讨论】:

    【解决方案2】:

    你可以这样做:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多