簡體   English   中英

Twisted Python接口實例可以不實現該接口的所有功能嗎?

[英]Can Twisted Python interface instance not implementing all functions of that interface?

在瀏覽本博客中的示例時,我發現當ClientFactory實例(它是PoetryClientFactory的一個參數)或Protocol實例(它是PoetryProtocol的一個參數)沒有實現為ClientFactory或Protocol接口定義的所有功能時。 ClientFactory接口實現startedConnecting,clientConnectionFailed和clientConnectionLost,但PoetryClientFactory不實現startedConnecting和clientConnectionLost。 怎么了?

# This is the Twisted Get Poetry Now! client, version 2.0.

# NOTE: This should not be used as the basis for production code.

import datetime, optparse

from twisted.internet.protocol import Protocol, ClientFactory


def parse_args():
    usage = """usage: %prog [options] [hostname]:port ...

This is the Get Poetry Now! client, Twisted version 2.0.
Run it like this:

  python get-poetry.py port1 port2 port3 ...

If you are in the base directory of the twisted-intro package,
you could run it like this:

  python twisted-client-2/get-poetry.py 10001 10002 10003

to grab poetry from servers on ports 10001, 10002, and 10003.

Of course, there need to be servers listening on those ports
for that to work.
"""

    parser = optparse.OptionParser(usage)

    _, addresses = parser.parse_args()

    if not addresses:
        print parser.format_help()
        parser.exit()

    def parse_address(addr):
        if ':' not in addr:
            host = '127.0.0.1'
            port = addr
        else:
            host, port = addr.split(':', 1)

        if not port.isdigit():
            parser.error('Ports must be integers.')

        return host, int(port)

    return map(parse_address, addresses)


class PoetryProtocol(Protocol):

    poem = ''
    task_num = 0

    def dataReceived(self, data):
        self.poem += data
        msg = 'Task %d: got %d bytes of poetry from %s'
        print  msg % (self.task_num, len(data), self.transport.getPeer())

    def connectionLost(self, reason):
        self.poemReceived(self.poem)

    def poemReceived(self, poem):
        self.factory.poem_finished(self.task_num, poem)


class PoetryClientFactory(ClientFactory):

    task_num = 1

    protocol = PoetryProtocol # tell base class what proto to build

    def __init__(self, poetry_count):
        self.poetry_count = poetry_count
        self.poems = {} # task num -> poem

    def buildProtocol(self, address):
        proto = ClientFactory.buildProtocol(self, address)
        proto.task_num = self.task_num
        self.task_num += 1
        return proto

    def poem_finished(self, task_num=None, poem=None):
        if task_num is not None:
            self.poems[task_num] = poem

        self.poetry_count -= 1

        if self.poetry_count == 0:
            self.report()
            from twisted.internet import reactor
            reactor.stop()

    def report(self):
        for i in self.poems:
            print 'Task %d: %d bytes of poetry' % (i, len(self.poems[i]))

    def clientConnectionFailed(self, connector, reason):
        print 'Failed to connect to:', connector.getDestination()
        self.poem_finished()


def poetry_main():
    addresses = parse_args()

    start = datetime.datetime.now()

    factory = PoetryClientFactory(len(addresses))

    from twisted.internet import reactor

    for address in addresses:
        host, port = address
        reactor.connectTCP(host, port, factory)

    reactor.run()

    elapsed = datetime.datetime.now() - start

    print 'Got %d poems in %s' % (len(addresses), elapsed)


if __name__ == '__main__':
    poetry_main()

我不確定我要問的是什么,但是從本質上講,如果您不需要對某個事件采取行動(例如,當客戶端開始連接或連接斷開時),則不需要實現該功能。 它主要只是一個界面。 如果您不實現這些功能,則會從ClientFactoryProtocol或您繼承的任何類中調用一個不執行任何操作的空函數。

如果您自己實現接口,則它看起來像這樣:

from zope.interface import implementer
from twisted.internet.interfaces import IProtocol
@implementer(IProtocol)
class MyProtocol(object):
    " ... "

在這種情況下,您確實需要實現所有方法,因為此@implementer聲明僅表示您打算提供所有相關方法。

但是,在Twisted中更常見的做法是子類化,如下所示:

from twisted.internet.protocol import Protocol
class MyProtocol(Protocol, object):
    " ... "

這種情況下,你並不需要實現所有的方法,因為Protocol的超類已經提供了對所有方法的實現IProtocol 通常,Twisted提供了一個超類,該類具有Twisted應用程序開發人員必須實現的許多更常用接口的所有方法的默認版本或空版本。

我也不太確定您要問什么。

IMO,獲取github的源代碼是最快的學習方法。 如您所見, startedConnectingclientConnectionLost (不過為空代碼)具有默認實現。

因此,您只需要實現所需的回調,而無需實現該接口中定義的所有方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM