Search code examples
pythonserial-port

Python - Class from Serial


how do I create a class that Inheritates from serial using the python serial module?

I need to create a module so another user can import to his code and create an object by just passing the COM.

This is my module, called py232

from serial import Serial

class serialPort(Serial):

def __init__(self, COM):
    serial.__init__(self)
    self.COMPort = COM
    self.baudrate = 9600
    self.bytesize = 8
    self.stopbits = serial.STOPBITS_ONE
    self.parity = serial.PARITY_NONE
    self.timeout = 2

    #serialPort = serial.Serial(port=self.COMPort, baudrate= self.baudrate, stopbits= self.stopbits, parity= self.parity, timeout= self.timeout)
    self.createSerial()
    
def createSerial(self):        
    sPort = serial.Serial(port = self.COMPort, baudrate=self.baudrate, bytesize=self.bytesize, timeout= self.timeout, stopbits = self.stopbits, parity=self.parity)    
    return sPort     

I am trying to use it in another script:

import py232
s = py232.serialPort('COM6')

s.sndSerial('test')

Solution

  • Why don't you just create an instance of serial in a function. No need to create a sub-class.

    from serial import Serial
    
    def create_serial(port):
        s = Serial(
            port,
            baudrate=9600,
            bytesize=8,
            timeout=2,
            # etc
        )
        return s
    

    It can then be used in another script.

    import py232
    
    s = py232.create_serial('COM6')