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):
    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)
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')

Asked By: AlexMacabu



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(
        # 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.