python/twisted - 这段代码有什么问题?

python/twisted - what is wrong with this code?

我正在学习 Python 并且目前专注于 Twisted...我正在做一个教程练习,但我似乎无法理解为什么这个代码的第二个版本中的修改是导致 'count' 函数在反应器启动之前执行。所有已更改的是向函数添加 's' 参数。

工作:

class Countdown(object):

counter = 5

def count(self):
    if self.counter == 0:
        reactor.stop()
    else:
        print self.counter, '...'
        self.counter -= 1
        reactor.callLater(1, self.count)

from twisted.internet import reactor

reactor.callWhenRunning(Countdown().count)

print 'Start!'
reactor.run()
print 'Stop!'

损坏:

class Countdown(object):

counter = 5

def count(self,s):
    if self.counter == 0:
        reactor.stop()
    else:
        print self.counter, '...'
        self.counter -= 1
        reactor.callLater(1, self.count(1))

from twisted.internet import reactor

reactor.callWhenRunning(Countdown().count(1))

print 'Start!'
reactor.run()
print 'Stop!'

这是回溯:

Traceback (most recent call last):
  File "C:\Python27\twistedexample\basic-twisted\countdown.py", line 15, in <module>
    reactor.callWhenRunning(Countdown().count(1))
  File "C:\Python27\twistedexample\basic-twisted\countdown.py", line 11, in count
    reactor.callLater(1, self.count(1))
  File "C:\Python27\twistedexample\basic-twisted\countdown.py", line 11, in count
    reactor.callLater(1, self.count(1))
  File "C:\Python27\twistedexample\basic-twisted\countdown.py", line 11, in count
    reactor.callLater(1, self.count(1))
  File "C:\Python27\twistedexample\basic-twisted\countdown.py", line 11, in count
    reactor.callLater(1, self.count(1))
  File "C:\Python27\twistedexample\basic-twisted\countdown.py", line 11, in count
    reactor.callLater(1, self.count(1))
  File "C:\Python27\twistedexample\basic-twisted\countdown.py", line 7, in count
    reactor.stop()
  File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 580, in stop
  "Can't stop reactor that isn't running.")
  ReactorNotRunning: Can't stop reactor that isn't running.

感谢任何对此的意见,我觉得我在这里遗漏了一些重要的东西,不想跳过它。

第一个版本的代码传递了对函数 count 的引用(以便以后可以调用它),而损坏的代码版本传递了 结果count(1) 的函数调用的 ,这将是 None(因为 count 没有 return 值)。所以你基本上所做的是改变这个:

reactor.callWhenRunning(Countdown().count)

对此:

reactor.callWhenRunning(None)

除此之外,您 立即 呼叫 count(1) 而不是为以后的呼叫注册!这解释了您看到的错误,因为在您到达 reactor.run().

行之前倒计时是 运行

这同样适用于调用 count(1) 的行 reactor.callLater(1, self.count(1)),可能返回 None,并且实际上没有向 callLater.[=23= 注册任何函数]