执行超时。以下代码有什么问题?

2024-05-23 16:09:31 发布

您现在位置:Python中文网/ 问答频道 /正文

程序第一次打印过期。我期待的代码打印“未过期”至少4次之前打印过期。有人能解释一下原因并帮我改正代码吗。谢谢

import time
TIMEOUT =  5

class Timer ():
    def __init__(self):
        self.timeout = time.time()+TIMEOUT
    def isExpired ():
        return time.time() > self.timeout

timing = Timer()

def main():
    while 1:
        if timing.isExpired:
            print "Expired"
            return
        else:
            print "Not expired"
            print "sleeping for 1 second"
            time.sleep(1)

if __name__== "__main__":
    main()

Tags: 代码self程序returniftimemaindef
2条回答

您每次都在创建一个Timer实例。把它从循环中拿走,否则你的while循环永远不会终止。此外,还需要调用timing.isExpired,因为它是一个方法。所以你的代码应该是:

import time
TIMEOUT = 60 * 5

class Timer ():
    def __init__(self):
        self.timeout = time.time()+TIMEOUT
    def isExpired (self):
        return time.time() > self.timeout


def main():
    timing = Timer()
    while 1:
        if timing.isExpired():
            print "Expired"
            return
        else:
            print "Not expired"
            print "sleeping for 1 second"
            time.sleep(1)

您有几个问题:

  1. 你没有给你的isExpired方法一个自我论证。将其定义为def isExpired(self):

  2. 您正在每个循环迭代中创建一个新的计时器实例。将timing = Timer()移出while循环。

  3. timing.isExpired是对方法对象iself的引用(在布尔上下文中总是true)。你需要做timing.isExpired()才能真正调用它。

这些都是与Timer无关的基本Python问题。阅读the Python tutorial学习如何使用类等等。你知道吗

相关问题 更多 >