获取/设置序列类属性

时间:2014-10-07 07:31:24

标签: python inheritance pyserial

我正在使用PySerial连接到Threaded连接。这是我简化的第一类继承Thread并运行serial:

from threading import Thread
import serial, inspect

class Serial1(Thread):

def __init__(self,main_queue,port = "COM1")

    self.ser = serial.Serial()
    self.queue = main_queue
    self.port = port

def open(self):

    self.ser.port = self.port
    if self.ser.isOpen():
        self.ser.close()
    self.ser.open()
    Thread.__init__(self)
    self.start()

之后我创建了另一个继承Thread并使用Serial1:

的类似的Serial2
from Queue import Queue
from threading import Thread
import serial1

class Serial2(Thread):

def __init__(self,main_queue,port = "COM2")

    self.ser = serial1.Serial1()
    self.queue = main_queue
    self.port = port

def open(self):
    self.ser = serial1.Serial1(self.queue, self.port)
    if self.ser.open() == True:
        Thread.__init__(self)
        if self.isAlive() == False:
            self.start()

完成所有这些后,如何在Serial1和Serial2上设置/获取串口的端口属性?假设我在脚本中使用Serial1和Serial2:

from Queue import Queue
import serial2
import serial1

q1 = Queue(maxsize = 1)
q2 = Queue(maxsize = 1)

s1 = serial1.Serial1(q1, "COM4" )
s2 = serial2.Serial2(q2, "COM2" )

#get port value from Serial1 and Serial2
port1 = s1.port
port2 = s2.port

#set Serial1 and Serial2 port value
s1.port = "COM3"
s2.port = "COM1"

之前我曾尝试在Serial1中使用getter / setter,但它们导致无限递归:

def getport(self): 
    return self.port

def setport(self, port): #when first initialising self.port, it goes and get stuck here
    self.port = port

port = property(getport,setport)

1 个答案:

答案 0 :(得分:0)

嗯,这很令人尴尬。

我终于得到了一个答案,这个答案很短:

def getport(self): 
    return self.ser.port

def setport(self, port):
    self.ser.port = port

port = property(getport,setport)