2014-12-13 130 views
0

我需要一些帮助来获得东西。我是OOP的新手。从我扭曲的文档中看到的,更精确的协议类:http://twistedmatrix.com/documents/current/api/twisted.internet.protocol.Protocol.html 我了解,这个类是喜欢和接口定义3种方法,我应该重写,并把代码中他们作为下面的经典例子显示:扭曲的框架Python

from twisted.internet.protocol import Protocol 

class Echo(Protocol): 

    def dataReceived(self, data): 
     self.transport.write(data) 

但是,我没有得到,我无法找到这个代码是如何成功运行的,当协议类不包含实际代码时,只是方法的定义。协议如何同时成为一个类和接口(它被创建为Class,但只包含方法的定义)?运行并响应事件的实际代码在哪里,以便它可以调用已定义的方法?

+0

扭曲的主要原因是:'不要打电话给我们,我们会打电话给你。所以是的,抽象协议类不应该包含任何实际的代码,只是定义。你称之为“代码的主要部分”是[Twisted.Reactor](http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.reactor.html)。但是,在真正需要之前,您不应该打扰自己,只需开始编写网络服务的_actual_部分,而将剩下的部分留给框架。 – user3159253 2014-12-13 07:10:58

+0

“成功运行”是什么意思?这个程序在运行时什么也不做。 “没有实际的代码”是什么意思?有一行“实际”代码(我认为它的意思是“方法的实现”:'self.transport.write(data)'。你是什么意思的“它创建为类”?为了这个问题应该是有用的,它必须是一个很窄的范围,并且包括(例如)你尝试解决这个问题的步骤,以及为什么它们不适合你。 – Glyph 2014-12-15 00:10:25

回答

1

检查了这一点(采取从扭曲的github上页):https://github.com/twisted/twisted/blob/trunk/twisted/internet/protocol.py

协议是BaseProtocol,其也以相同的.py文件中定义的子类。

class Protocol(BaseProtocol): 
""" 
This is the base class for streaming connection-oriented protocols. 
If you are going to write a new connection-oriented protocol for Twisted, 
start here. Any protocol implementation, either client or server, should 
be a subclass of this class. 
The API is quite simple. Implement L{dataReceived} to handle both 
event-based and synchronous input; output can be sent through the 
'transport' attribute, which is to be an instance that implements 
L{twisted.internet.interfaces.ITransport}. Override C{connectionLost} to be 
notified when the connection ends. 
Some subclasses exist already to help you write common types of protocols: 
see the L{twisted.protocols.basic} module for a few of them. 
""" 

def logPrefix(self): 
    """ 
    Return a prefix matching the class name, to identify log messages 
    related to this protocol instance. 
    """ 
    return self.__class__.__name__ 


def dataReceived(self, data): 
    """Called whenever data is received. 
    Use this method to translate to a higher-level message. Usually, some 
    callback will be made upon the receipt of each complete protocol 
    message. 
    @param data: a string of indeterminate length. Please keep in mind 
     that you will probably need to buffer some data, as partial 
     (or multiple) protocol messages may be received! I recommend 
     that unit tests for protocols call through to this method with 
     differing chunk sizes, down to one byte at a time. 
    """ 

def connectionLost(self, reason=connectionDone): 
    """Called when the connection is shut down. 
    Clear any circular references here, and any external references 
    to this Protocol. The connection has been closed. 
    @type reason: L{twisted.python.failure.Failure} 
    """