D
D
da da2021-04-20 18:33:29
Python
da da, 2021-04-20 18:33:29

How to improve this code (in terms of OOP)?

class MicroPythonBoard():

    def __init__(self, port, baudrate):
        self.serialPort=serial.Serial(port, baudrate)
    
    def putCursorOnNewLine(self):
        self.serialPort.write(b"\r")

    def writeln(self, string):
        """ Write a line to serial poart """
        self.serialPort.write( bytes(string, "ascii"))
        self.putCursorOnNewLine()
    

    def write(self, string):
        """write a string to serial port """
        self.serialPort.write( bytes(string, "ascii") )


    def writeFile(self, pathToFile, fileName):
        """
        pathToFile - path to file on your computer
        fileName - Name of file on your MicroPython board
        """
        with open(pathToFile) as file:
            
            self.serialPort.write((chr(5).encode("ascii"))) # write <CTRL+E> (PASTE MODE)

            self.serialPort.write((f'with(open("{fileName}", "w")) as f:').encode("ascii"))

            self.putCursorOnNewLine()

            self.serialPort.write(b"    f.write(r'''")

            self.putCursorOnNewLine()

            for line in file.readlines():
                self.serialPort.write(line.encode("ascii"))
            
            self.putCursorOnNewLine()
            self.serialPort.write(b"''')")

            self.serialPort.write(chr(4).encode("ascii")) # write <CTRL+D> (CLOSE PASTE MODE)

            print("DONE")
    
    def readLastLine(self):
        all_text=self.serialPort.read_all()
        last_line=all_text.split(b"\r")[-1]
        return last_line

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MinTnt, 2021-04-20
@IIggoorrII

Even if it's not for me to say. But OOP is moving towards minimizing duplicate lines that do the same job.
For example. The same line is repeated here.

self.serialPort.write( bytes(string, "ascii") )
def writeln(self, string):
        """ Write a line to serial poart """
        self.serialPort.write( bytes(string, "ascii"))
        self.putCursorOnNewLine()
    

    def write(self, string):
        """write a string to serial port """
        self.serialPort.write( bytes(string, "ascii") )

So everything can be reduced to one function by just adding one more input parameter
reduce to one function
def write(self, string, nextline=False):
        """write a string to serial port """
        self.serialPort.write( bytes(string, "ascii") )
        if nextline:
            self.putCursorOnNewLine()

#И далее вызывать, функцию write('text') как и раньше, а функцию writeln - как write('text', True)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question