python 类方法在调用时会提示

标签 python autobahn

我有一个类方法:

class MyServerProtocol(WebSocketServerProtocol):

    @classmethod
    def send(cls, text):
        cls.sendMessage(cls, text)

    def onMessage(self, payload, isBinary):
        msp=MyServerProtocol
        msp.send('test')

我正在尝试调用这个类方法(作为现在的测试,从类内部),我得到:

exceptions.TypeError: unbound method sendMessage() must be called with MyServerProtocol instance as first argument (got type instance instead)

它正在等待一个实例并提示它得到了一个实例...任何人都知道如何正确调用它。一旦我让它工作,我就可以在另一个类中进行测试,只是想在迁移之前先让它工作。

编辑:

我已修改代码以按如下方式调用该方法,但它现在仍然有效。

class MyServerProtocol(WebSocketServerProtocol):

    def onMessage(self, payload, isBinary):

        myInput = literal_eval(payload)
        cg = coreg.DataGatherCg()
        cg.test(myInput, self)


    def send(self, text):
        self.sendMessage(text)

class DataGatherCg():

    def test(self, myInput, obj):
        obj.send(myInput)

来自 AutoBahn 的 SendMessage 如下,在传递 self 后,我收到一个断言错误:

def sendMessage(self,
                payload,
                isBinary=False,
                fragmentSize=None,
                sync=False,
                doNotCompress=False):
    """
    Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.sendMessage`
    """
    assert(type(payload) == bytes)

    if self.state != WebSocketProtocol.STATE_OPEN:
        return

    if self.trackedTimings:
        self.trackedTimings.track("sendMessage")

    # (initial) frame opcode
    #
    if isBinary:
        opcode = 2
    else:
        opcode = 1

    self.trafficStats.outgoingWebSocketMessages += 1

    # setup compressor
    #
    if self._perMessageCompress is not None and not doNotCompress:
        sendCompressed = True

        self._perMessageCompress.startCompressMessage()

        self.trafficStats.outgoingOctetsAppLevel += len(payload)

        payload1 = self._perMessageCompress.compressMessageData(payload)
        payload2 = self._perMessageCompress.endCompressMessage()
        payload = b''.join([payload1, payload2])

        self.trafficStats.outgoingOctetsWebSocketLevel += len(payload)

    else:
        sendCompressed = False
        l = len(payload)
        self.trafficStats.outgoingOctetsAppLevel += l
        self.trafficStats.outgoingOctetsWebSocketLevel += l

    # explicit fragmentSize arguments overrides autoFragmentSize setting
    #
    if fragmentSize is not None:
        pfs = fragmentSize
    else:
        if self.autoFragmentSize > 0:
            pfs = self.autoFragmentSize
        else:
            pfs = None

    # send unfragmented
    #
    if pfs is None or len(payload) <= pfs:
        self.sendFrame(opcode=opcode, payload=payload, sync=sync, rsv=4 if sendCompressed else 0)

    # send data message in fragments
    #
    else:
        if pfs < 1:
            raise Exception("payload fragment size must be at least 1 (was %d)" % pfs)
        n = len(payload)
        i = 0
        done = False
        first = True
        while not done:
            j = i + pfs
            if j > n:
                done = True
                j = n
            if first:
                self.sendFrame(opcode=opcode, payload=payload[i:j], fin=done, sync=sync, rsv=4 if sendCompressed else 0)
                first = False
            else:
                self.sendFrame(opcode=0, payload=payload[i:j], fin=done, sync=sync)
            i += pfs

    # if self.debug:
    #   self.log.debug("Traffic statistics:\n" + str(self.trafficStats))

最佳答案

无法用最小的示例重现该错误,但似乎是在说 sendMessage() 不是类方法。如果不传递实例本身,则无法从类方法调用实例方法。

尝试为 send() 添加另一个参数来保存实例,然后为该参数传递 self 。像这样的东西:

class MyServerProtocol(WebSocketServerProtocol):

    @classmethod
    def send(cls, self, text):
        self.sendMessage(text)

    def onMessage(self, payload, isBinary):
        msp=MyServerProtocol
        msp.send(self, 'test')

尽管此时,您不妨将 send() 设为实例方法。

关于python 类方法在调用时会提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093566/

相关文章:

python - Autobahn 可以使用自定义 json 编码器吗?

Android - NullPointerException 错误

python - Django:从表单中保存外键

python - 是否可以通过代码对象访问内部函数和类?

python - 使用 Autobahn WebSocket 库使用 sendMessage 进行 CouchDB 更改

python - 高速公路网络套接字

python - 当网络完全收敛时停止 Keras 训练

python - 使用列表理解从空值返回列表项

python - 如何通过在pyglet窗口中用鼠标拖动将.png从x,y拖动到x1,y1