OOP:与另一个类(Filter)的多个实例共享一个类(硬件端口)的实例

2024-09-27 07:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序(用户界面)从5个不同的节点收集数据,并对接收到的数据进行过滤(移动平均、winsormean、mode和许多其他过滤器)。整个程序设计使用3个类

  • 类#1:SerialComm类为 只有一个串行端口,所有节点都物理连接到该端口。

  • 类#2:StatusBar类提供更新用户的状态栏 接口(错误消息、对密钥的用户操作的确认 按)。

  • 类#3:Node类保存5个节点中的每个节点的数据 通过串行接口收集的数据通过各种方法进行后处理 过滤技术。

串口可以有一个实例,但是每个节点实例都需要使用这个实例来get_data()。类似地,StatusBar也是唯一的一个,目前我正在将SerialCommStatusBar的实例传递给5个节点的每个实例,如下所示。你知道吗

我不喜欢这种将实例传递给每个对象的方法,有没有更好的方法来处理这个问题?

class StatusBar:

   def __init__(self):
      self.status_message = 'none'

   def get_status_msg(self):
      return self.status_message

   def update_status_msg(self, msg):
      self.status_message = msg


class SerialComm:
   def __init__(self, portnum, obj_statusbar, baud=19200):

     # More code follows

     self._portNumber = portnum
     self.statusMsg = obj_statusbar

     try:
        self._portInstance = serial.Serial(self._portNumber,baud, timeout=0.05)
     except IOError, e:
        print e

   def write_bytes(self,len):
     # Write method
   def read_bytes(self,len):
     # read method

class Node:
   def __init__(self,obj_statusbar, obj_comm, n_address, n_location=0, ref_rssi=-50,
                n_color=(255,255,0)):
     self._address= n_address
     self._location=n_location
     self._status_bar =obj_statusbar
     self._comm_port = obj_comm

   def read_sensor(self):          
        if(  self._comm_port.read_bytes(10) != "112233445566778899AA"):
               self._status_bar.update_status_msg(" Data out of boundary")  
     ...
     # More code follows
status_bar = StatusBar()
comm_interface = SerialComm('COM4', status_bar, 19200)

Node_1 = Node(status_bar,comm_interface,0x9,Point(0, 0),-57,RED)
Node_2 = Node(status_bar,comm_interface,0xA,Point(2, 0),-57,GREEN)
Node_3 = Node(status_bar,comm_interface,0xB,Point(1, 2),-57,BLUE)
Node_4 = Node(status_bar,comm_interface,0xC,Point(1, 3),-57,ORANGE)
Node_5 = Node(status_bar,comm_interface,0xD,Point(1, 0),-57,BPINK)

Tags: 数据实例selfnodeobj节点defstatus
1条回答
网友
1楼 · 发布于 2024-09-27 07:18:20

这种方法很好。构造函数的关键是必须为它提供最少数量的参数,以便它在实例化之后可以运行。如果您的节点依赖于statusbar实例,那么应该将其传递给每个节点。你知道吗

这使您可以灵活地在不同的关系中拥有多个节点、状态栏和SerialComm对象。这对于模拟和单元测试尤其重要。不要被诱惑去使用某种全局黑客,比如使用单例或静态变量作为单例。这些很快就变得很难测试。你知道吗

相关问题 更多 >

    热门问题