繁体   English   中英

如何在Python中从其他类调用类方法?

[英]How Can I Call a Class Method From a Different Class in Python?

我有一个Raspberry Pi:

  • 通过Xbee到Arduino的串行接口
  • 网页的WebSocket服务器界面(html / javascript)

我写了一个Python脚本来协调通信(我是Python的新手)。 它包含:

  • 串行接口类
  • WebSocket接口类

我正在尝试在网页和Arduino之间中继数据。 具体来说,我试图从Serial类 调用 Websocket类中 的“发送”方法,并从WebSocket类调用 Serial类中 的“发送”方法

我花了很多时间阅读和研究,但我无法弄清楚。 这是我现在的代码。 我得到的具体错误是“ sendSocket()恰好接受2个参数(给定3个)。

# server.py

DEBUG = True;

import serial
import time
import sys
import json
import os
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from twisted.internet import reactor
from twisted.internet import task

# I think I need these for the instances?
global socket, serial

# ---------------------------------
# WebSocket Interface
# ---------------------------------
class HaSocketProtocol(WebSocketServerProtocol):
    # I'm not sure of any other way to incorporate the instance
    global serial

    def __init__(self):
        pass

    def onConnect(self, request):
        debug("Client connected")

    def onOpen(self):
        debug("WebSocket Server Open")

    def onMessage(self, payload, isBinary):
        if not isBinary:
            payload = payload.decode('utf8')
            debug("Incoming socket message: {} -- Writing as-is to xbee".format(payload))
            # Here is where I'm trying to send the data I received out the serial port using the SerialInterface class method
            self.sendSerial(serial, payload)

    def onClose(self, wasClean, code, reason):
        debug("WebSocket connection closed - {}".format(reason))

    # Socket server sending over socket    
    def send(self, message):
        self.sendMessage(message)

    # Here is where I'm trying to link them 
    @classmethod
    def sendSerial(SerialInterface, message):
        SerialInterface.send(message)

# ---------------------------------
# Serial Interface
# ---------------------------------
class SerialInterface:
    xbee = None
    # trying to iunclude the instance
    global socket

    def __init__(self, devname, baud, to):
        self.xbee = serial.Serial(devname, baud, timeout=to)
        debug(self.xbee)

    def check(self):
        incoming = None
        # will timeout if there's no data to be read
        incoming = self.xbee.readline().strip()
        if incoming != None and incoming != "":
            self.handle(incoming)

    # serial send over serial
    def send(self, message):
        self.xbee.write(message)
        self.xbee.write("\n")

    # here is where i'm trying to link them    
    @classmethod
    def sendSocket(HaSocketProtocol, message):
        HaSocketProtocol.send(message)        

    def handle(self, incoming):
        debug("Incoming serial: {}".format(incoming))

        # ...
        # my logic is in here that leads to several instances where I
        # create a command string that I send over the serial port
        # ...

        socketMessage = "ArduinoCommand"
        self.sendSocket(socket, socketMessage)

# ------------------------------
# main
# ------------------------------
def main():
    global socket, serial

    serial = SerialInterface('/dev/ttyUSB0', 9600, 1)
    socket = HaSocketProtocol()

    factory = WebSocketServerFactory("ws://localhost:9000", debug=False)
    factory.protocol = socket

    # check Serial port for data every 1 second
    ser = task.LoopingCall(serial.check)
    ser.start(1.0)

    reactor.listenTCP(9000, factory)
    reactor.run()

def debug(msg):
    if DEBUG:
        print "{}\n".format(msg)    


main()

我认为您需要在HaSocketProtocol.send()方法上放置一个@classmethod“ decorator”,就像您在其他方法上一样。

class方法自动获取该类:

@classmethod
def myMethod(cls):
   pass

这就是为什么会出现此错误的原因-2个参数+ cls =3。但是该方法仅需要两个。 因此,您必须在sendSocket方法中添加“ cls”参数

 @classmethod
    def sendSocket(cls, HaSocketProtocol, message):
        HaSocketProtocol.send(message)        

如果您的方法中确实不需要cl,请将@classmethod替换为@staticmethod

PS检查其他类方法

您的类方法应如下所示:

@classmethod
def sendSocket(cls, hsockprotocol, message):
    hsockprotocol.send(message)

注意第二个参数的更改。 它应该只是一个变量,而不是类引用。

事实证明,这个问题实际上是有关如何实现Autobahn框架的,而不是有关如何使用Python编程的问题。 对我来说,用JavaScript重写并将其放到Node.js上更容易。 运行很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM