Labs / Python OOP

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 16 Python Implementation of Classes and Objects - Polymorphism, Method Overriding and Open Closed Principle

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents

Abstract:

This article mainly introduces how subclasses implement method overriding of parent classes when creating custom classes in Python, the definition of method overriding, and the basic concept of polymorphism, as well as the Open Closed Principle.

FreakStudio's Blog

Previous Recommendations:

You who study embedded systems still don't know Object Oriented? ?!

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 00 Introduction to Object Oriented Design Methodology

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 01 Basic Concepts of Object Oriented Programming

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 02 Python Implementation of Classes and Objects - Creating Classes with Python

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 03 Python Implementation of Classes and Objects - Adding Attributes to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 04 Python Implementation of Classes and Objects – Adding Methods to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 05 Python Implementation of Classes and Objects - PyCharm Code Tab

The most beginner-friendly Object Oriented programming tutorial on the entire network: 06 Python implementation of classes and objects - data encapsulation of custom classes

The most beginner-friendly Object Oriented programming tutorial across the entire network: 07 Python implementation of classes and objects - type annotations

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 08 Python Implementation of Classes and Objects - @property Decorator

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 09 Python Implementation of Classes and Objects - Relationships Between Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 10 Python Implementation of Classes and Objects - Class Inheritance and Liskov Substitution Principle

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 11 Python Implementation of Classes and Objects - Subclass Calling Parent Class Methods

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Internet: 12 Python Implementation of Classes and Objects - Using the logging Module in Python to Output Program Running Logs

The Best Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 13 Python Implementation of Classes and Objects – Installation and Usage of Sourcetrail, a Visual Code Reading Tool

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 14 Python Implementation of Classes and Objects – Static Methods and Class Methods of Classes

The most beginner-friendly Object Oriented programming tutorial across the network: 15 Python implementation of classes and objects - the __slots__ magic method

More exciting content can be found here:

Speed Up Your Python: A Quick Guide to Python Parallel Computing

Understand the Debugging Principle of CM3 Microcontroller in One Article

After half a month of dedicated work, the comprehensive summary of embedded technology stack is now released

The "Secret Martial Arts Manual" for Computer Science Competitions

Document and Code Acquisition:

You can download the document via the following link:

https://github.com/leezisheng/Doc

1 0 19

This document mainly introduces how to use Python for Object Oriented programming, and requires readers to have a basic understanding of Python syntax and single-chip microcomputer development. Compared with other blogs or books that explain Python Object Oriented programming, this document is more detailed and focuses on embedded host computer applications, taking the common serial port data transmission and reception, data processing, dynamic graph drawing and other functions between the host computer and the lower computer as application examples. Meanwhile, Sourcetrail code software is used for visual reading of the code to facilitate readers' understanding.

The link to obtain the relevant sample code is as follows:

https://github.com/leezisheng/Python-OOP-Demo

Main Text

After a subclass inherits the methods of its parent class, it can provide a new implementation version for the existing methods of the parent class, and this action is called method overriding (override). If the functions of the methods in your parent class cannot meet your requirements, you can override the methods of the parent class in the subclass. Here, in the ReadSerial method of the SerialClass class, we use the statement `data = self.dev.readline ()` to read data line by line. What if we want to read data by the number of bytes? How should we operate then? Let's look at the following code:

class DevClass(SerialClass):
    def __init__(self,port:str = "COM1"):
        super().__init__(port)

    # Turn on the device
    def StartDev(self):
        super().OpenSerial()
        print("START Dev :" + self.dev.port)

    def ReadSerial(self,byte_size):
        if super().RetSerialState():
            data = self.dev.read(byte_size)
            data = int(data.decode('utf-8', 'replace'))
            return data

if __name__ == "__main__":

    d = DevClass("COM1")
    d.StartDev()

    while True:
        data = d.ReadSerial(1)
        print(data)

Here, we have rewritten the ReadSerial method to read one byte at a time, and the operation result is as follows:

8 1 2 5 V2.6 COM1 115200

Through method overriding, we can make the same behavior of the parent class have different implementation versions in subclasses; when we call this method that has been overridden by a subclass, different subclass objects will exhibit different behaviors, and this is polymorphism.

To understand the benefits of polymorphism, we need to write another function, which is mainly used to determine whether the serial port code of the serial port object is enabled. The sample code is as follows:

# Check whether the serial port of the serial class object is open
def IsSerialConnected(serialclass):
    return serialclass.RetSerialState()

Here, we can not only pass in the SerialClass class, but also its subclasses:

    s = SensorClass()
    m = MasterClass()
    d = DevClass()
    # Check whether it is an inheritance relationship
    issub = issubclass(SensorClass, SerialClass)
    print(issub)

    # The built-in isinstance() method essentially checks the data type of an object
    # isinstance is used to check the relationship between an instance and a class
    isin = isinstance(s, SerialClass)
    print(isin)

    # Check whether the serial port of object s - SensorClass is open
    print(IsSerialConnected(s))
    # Check whether the serial port of object m - MasterClass is open
    print(IsSerialConnected(m))
    # Check whether the serial port of object d - DevClass is open
    print(IsSerialConnected(d))

Actually, we will find that when adding a new subclass of SerialClass, we don't need to make any modifications to IsSerialConnected (). In fact, any function or method that takes SerialClass as a parameter can run normally without any changes, and the reason lies in polymorphism.

For a variable, we only need to know that it is of the SerialClass type, without needing to know its exact subtype, and we can safely call the RetSerialState () method. The specific RetSerialState () method that gets invoked acts on SensorClass, MasterClass, or DevClass objects, and is determined by the exact type of the object at runtime. This is the true power of polymorphism: the caller only needs to initiate the call without concerning themselves with the underlying details. When we add a new subclass of SerialClass, we only need to ensure that the RetSerialState () method is implemented correctly, without having to worry about how the original code invokes it.This is the famous "Open-Closed" Principle:

Open for extension: allowing the addition of new subclasses of SerialClass;

Closed for modification: there is no need to modify functions such as IsSerialConnected () that depend on the SerialClass type.

Actually, in an inheritance relationship, if the data type of an instance is a certain subclass, then its data type can also be regarded as that of the parent class.

SerialClass1
347622978