静态语言实现回调的方法有待后续补充;
Twisted Introduction from KRONDO by Dave Peticolas, Part6中使用的源代码twisted-client-3\get-poetry.py很好的阐述了python中实现回调(call back)的方法,下面是get-poetry.py的简化版: from twisted.internet.protocol import Protocol, ClientFactory
class PoetryProtocol(Protocol): poem = '' def dataReceived(self, data): self.poem += data def connectionLost(self, reason): self.poemReceived(self.poem) def poemReceived(self, poem): self.factory.poem_finished(poem)
class PoetryClientFactory(ClientFactory): protocol = PoetryProtocol
def init(self, callback): self.callback = callback # 将回调函数作为属性写入facotry对象中
def poem_finished(self, poem): self. callback (poem) # 神奇的是这个“属性”可以当方法用,只要在后面直接加括号和参数就OK了 def get_poetry(host, port, callback ): from twisted.internet import reactor factory = PoetryClientFactory(callback) reactor.connectTCP(host, port, factory)
if name == 'main': def got_poem (poem): poems.append(poem) if len(poems) == len(addresses): reactor.stop() for address in addresses: host, port = address get_poetry(host, port, got_poem ) # 将回调方法方法作为参数传给factory对象
回调方法的本质是:从服务器下载诗句,当下载完成时做某件事,如何做这件事(做这件事的步骤)就定义在回调函数get_poem中。同步方式下,下载完成等同于下载诗句的函数返回,异步方式下不能这么办,只能由感知到事件发生的对象运行回调函数这种方法达到目的。本例中,服务器在诗句下载完成后关闭与客户端的连接,所以客户端的protocol对象的 connectionLost方法(也是一个call back函数)首先感知到下载完成,然后调用自己对应的factory对象的poem_finished方法,在poem_finished方法中使用get_poem方法处理下载完的poem。这里的关键是我们用写入属性的方法将回调函数赋给factory对象,factory就可以在接到(来自于protocol对象的)通知的时候运行这个“属性方法”。Part 6的Figure 11很好的图示了上述过程。