我正在学习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!'
破损:
^{pr2}$回溯如下:
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
值)。所以你所做的基本改变是:为此:
^{pr2}$除此之外,您还可以立即调用
count(1)
,而不是为以后的调用注册它!这解释了您看到的错误,因为在到达reactor.run()
行之前倒计时正在运行。在这同样适用于}注册任何函数。在
reactor.callLater(1, self.count(1))
行,它调用count(1)
,可能返回None
,实际上没有向{相关问题 更多 >
编程相关推荐