Python – Class from Serial

Question:

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')
Asked By: AlexMacabu

||

Answers:

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')
Answered By: Gary Kerr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.