我正在学习Python并且目前专注于Twisted ......我正在进行一个教程练习,但我似乎无法理解为什么在此代码的第二个版本中修改会导致&# 39;计数'在反应堆启动之前执行的功能。所有改变的都是添加'函数的论证。
工作:
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.
对此的任何意见表示赞赏,我觉得我在这里遗漏了一些重要内容并且不想跳过它。
答案 0 :(得分:2)
代码的第一个版本传递对函数count
的引用(以便以后可以调用它),而代码的破坏版本传递结果 count(1)
的函数调用,它将是None
(因为count
没有return
值)。所以你基本上做了什么改变了这个:
reactor.callWhenRunning(Countdown().count)
到此:
reactor.callWhenRunning(None)
最重要的是,你立即调用count(1)
而不是注册它以便以后调用!这解释了您看到的错误,因为在您到达第reactor.run()
行之前倒计时正在运行。
这同样适用于调用reactor.callLater(1, self.count(1))
的行count(1)
,可能返回None
,而实际上并未使用callLater
注册任何函数。