Labs / Python OOP

The most beginner-friendly Object Oriented programming tutorial on the entire network: 50 Python function methods and interfaces - Interfaces and Abstract Base Classes

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

Contents
The most beginner-friendly Object Oriented programming tutorial on the entire network: 50 Python function methods and interfaces - Interfaces and Abstract Base Classes

Abstract:

In Python, both interfaces and Abstract Base Classes (ABCs) are used to define class structures and enforce subclasses to implement specific methods. Python does not have a built-in interface mechanism, but the behavior of interfaces can be simulated via Abstract Base Classes (ABCs).

FreakStudio's Blog

Previous Recommendations:

You who are learning embedded systems, don’t you even know Object Oriented yet? ?!

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 Course 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 across the entire 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 on the Whole Network: 05 Python Implementation of Classes and Objects - PyCharm Code Tab

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole 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 on the Whole 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 Network: 12 Python Implementation of Classes and Objects - Using Python's logging Module to Output Program Runtime Logs

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole 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 entire network: 15 Python implementation of classes and objects - the __slots__ magic method

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

The most beginner-friendly Object Oriented programming tutorial across the network: 17 Python implementation of classes and objects - duck typing and "file-like object"

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 18 Python Implementation of Classes and Objects - Multiple Inheritance and Serial Port Data Curve Plotting with PyQtGraph

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 19 Python Implementation of Classes and Objects – Using PyCharm to Automatically Generate File Comments and function Comments

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 20 Python Implementation of Classes and Objects – Implementation of Composition Relationship and CSV File Saving

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 21 Python Implementation of Classes and Objects - Multi-File Organization: Module and Package

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 22 Python Implementation of Classes and Objects - Exceptions and Syntax Errors

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 23 Python Implementation of Classes and Objects - Throwing Exceptions

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 24 Python Implementation of Classes and Objects - Exception Capture and Handling

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 25 Python Implementation of Classes and Objects - Python Determines Input Data Types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 26 Python Implementation of Classes and Objects - Context Managers and the with Statement

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 27 Python Implementation of Classes and Objects - Implementation of Exception Hierarchy and Custom Exception Classes in Python

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 28 Python Implementation of Classes and Objects - A Comprehensive Summary of Python Programming Principles, Philosophy and Specifications

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 29 Python Implementation of Classes and Objects - Assertions, Defensive Programming and the Usage of the help function

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 30 Python's Built-in Data Types - The object Root Class

The most beginner-friendly Object Oriented programming tutorial across the entire network: 31 Built-in data types in Python - Object and Type

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 32 Python's Built-in Data Types - Class and Instance

The most beginner-friendly Object Oriented programming tutorial on the entire network: 33 Built-in data types in Python – the relationship between objects and types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 34 Python's Built-in Data Types - Commonly Used Composite Data Types in Python: Tuples and Named Tuples

The most beginner-friendly Object Oriented programming tutorial on the entire network: 35 Python's built-in data types - docstrings and the __doc__ attribute

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 36 Python's Built-in Data Type - Dictionary

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 37 Common Composite Data Types in Python - Lists and List Comprehensions

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 38 Common Composite Data Types in Python – Implementing stack, Queue and Deque with Lists

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 39 Common Composite Data Types in Python – Sets

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 40 Common Composite Data Types in Python - Enumerations and Usage of the enum Module

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 41 Common Composite Data Types in Python - Queues (FIFO, LIFO, Priority Queue, Deque and Circular Queue)

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 42 Commonly Used Composite Data Types in Python - Collections Container Data Types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 43 Common Composite Data Types in Python - Extending Built-in Data Types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 44 Python Built-in functions and Magic Methods – Overriding Magic Methods of Built-in Types

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 45 Implementing Common Data Structures in Python – Linked List, Tree, Hash Table, Graph and Heap

The most beginner-friendly Object Oriented programming tutorial across the network: 46 Python function methods and interfaces - functions and event-driven frameworks

The most beginner-friendly Object Oriented programming tutorial across the network: 47 Python function methods and interfaces - Callback function

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 48 Python function Methods and Interfaces - Positional Arguments, Default Arguments, Variable Arguments and Keyword Arguments

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 49 Python function Methods and Interfaces – The Difference Between function and Methods, and Lambda Anonymous Functions

For more exciting content, you can check out:

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 ultimate summary of embedded technology stack is now released

The "Martial Arts Manual" for Computer Science Competitions

Avnet ZUBoard 1CG Development Board — A New Choice for Deep learning

Deploy SenseCraft Model to Grove Vision AI V2 Image Processing Module

Document and Code Acquisition:

You can download the document via the following link:

https://github.com/leezisheng/Doc

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 microcontroller 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 slave computer as application examples. Meanwhile, it uses the Sourcetrail code software to visualize the code for reading, so as to facilitate readers' understanding.

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

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

Body Text

1. Interface

1.1 Concept of Interface

In 1994, the Gang of Four (GoF) put forward a pivotal programming principle in their classic work *Design Patterns*, namely "program to interfaces, not implementations". The original English wording of this principle is "Program to an interface, not an implementation". Here, the so-called "interface" does not specifically refer to the interface definition of a particular programming language, but rather a cross-language concept. It represents a set of functions provided by developers to users, and understanding these functions is critical to programming practice.Simply put, an interface defines the tasks a program is supposed to accomplish, without involving specific implementation details. This principle has a profound impact on improving the scalability, maintainability and flexibility of code.

By defining interfaces, we can reduce the amount of code changes when the function that implements a specific function encounters a problem (which may be caused by using an unauthorized pirated module that is detected and sued, or by a library version change where an important function is renamed or removed), and encapsulate unstable implementations while exposing stable interfaces through the pattern of separating interfaces from implementations. When upstream and downstream systems use the functions we develop, they only need to use the list of functions declared in the interface. In this way, when the implementation changes, the code of the upstream system basically does not need to be modified, thereby reducing coupling and improving scalability.

At the same time, by defining interfaces, the system is divided into multiple small modules, each of which only needs to implement the interfaces it requires without concerning itself with the implementation details of other modules. In this way, when collaborating with others, we only need to modify the module that we implement for the corresponding interface, without having to alter other modules.

1.2 Implementation of the Interface

Common Object Oriented languages typically have a clear distinction between the interface and the implementation of a class. For example, some languages provide an explicit `interface` keyword, which is used to define the methods that a class must contain but does not require implementation. In such an environment, an abstract class provides an interface along with concrete implementations for some of its numerous methods. Any class can explicitly declare that it implements a certain interface.

Compared with languages such as Java, Go and C++, Python has a somewhat different interface design approach. These languages all provide an `interface` keyword for defining interfaces, whereas Python does not offer such a keyword. Python also differs noticeably from other languages in another aspect: it does not require a class that implements an interface to define all the abstract methods of that interface.

2. Implement interfaces using class inheritance

Here, we first define an interface for a data processing class, and specify that this class should have methods for data filtering, maximum value calculation, minimum value calculation, and Fourier transform. Meanwhile, we also define the parameters that need to be received during initialization, such as the data list, the number of filter points (taking average filtering as an example, it refers to the number of points for which the average value is calculated), and so on.

The sample code is as follows:

# Use the compound annotation feature provided by the typing module
from typing import List

# Define the data processing interface
class DateProcessInterface(object):
    def __init__(self,DateList:List[int],FilterLength:int):
        '''
        Initialization method
        :param DateList: Data list
        :param FilterLength: Number of points to apply data filtering to
        
        '''
        pass
    def DateFilter(self)->List:
        '''
        Data filtering
        :return: List
        '''
        pass
    def DateCalMax(self)->int:
        '''
        Calculate the maximum value of the data
        :return: int
        '''
        pass
    def DateCalMin(self)->int:
        '''
        Calculate the minimum value
        :return: int
        '''
        pass

During the process of defining this interface, although no specific operations are implemented, our main concern is that this interface class specifies the general methods for data processing, which can also be regarded as a specification: we will first perform preprocessing such as filtering on the data, and then calculate some time-domain features for analysis. DateProcessInterface is essentially a standard Python class, but since it resembles an interface, this class can be treated as an interface.

To use this interface, you first need to create a concrete class that inherits from DateProcessInterface — that is, this class acts as a subclass of the interface class, and provides concrete implementations for the abstract methods defined in the interface.

The sample code is as follows. Here we need to import the math library to use the sin function, import the random library to generate a random number sequence for simulating noise, and import the matplotlib library for plotting; the matplotlib library needs to be installed via conda or pip commands:

import math
import matplotlib.pyplot as plt
import random

# Create a concrete class that inherits from DateProcessInterface
class DateProcessClass(DateProcessInterface):
    def __init__(self,DateList:List[int],FilterLength:int):
        self.DateList       = DateList
        self.FilterLength   = FilterLength
        self.TempList       = [0] * (self.FilterLength)
    def DateFilter(self)->List:
        # Iterate over DateList
        for index,value in enumerate(self.DateList):
            # Treat each value as a new sensor value being passed in
            NowValue = value
            # Variable representing the sum of the list
            sum = 0
            for i in range(self.FilterLength-1):
                # Implement the list shift operation
                self.TempList[i] = self.TempList[i + 1]
                # Implement the list sum
                sum += self.TempList[i]
            self.TempList[self.FilterLength-1] = NowValue
            sum += self.TempList[self.FilterLength - 1]
            # Compute the average
            average = sum / self.FilterLength
            # Replace the original value with the computed average
            self.DateList[index] = average
        # After the computation, reset the elements in TempList to zero
        self.TempList = [0] * (self.FilterLength)
        return self.DateList
    def DateCalMax(self)->int:
        max_value = max(self.DateList)
        return int(max_value)
    def DateCalMin(self)->int:
        min_value = min(self.DateList)
        return int(min_value)

# Create an index list for l, mainly to provide the x-axis coordinates for the plot function
index = [x for x in range(0,100)]
# Generate a sine sequence
originalsignal = [math.sin(x)*10 for x in range(0,100)]
# Generate a random number sequence to simulate noise
noise = [random.uniform(0, 5) for x in range(0,100)]
# Add the elements of the two lists
signal = [x+y for x,y in zip(originalsignal,noise) ]
# Create the DateProcessClass class, passing in signal.copy()
# Create a copy of the signal sequence so that the original data of l is not changed
s = DateProcessClass(signal.copy(),10)
# Perform data filtering
filtersignal = s.DateFilter()
# Plot the curve
plt.plot(index,signal,'b')
plt.plot(index,filtersignal,'r')
# Display an image
plt.show()
# Print the maximum value of the signal
print("Signal Max value:",s.DateCalMax())
# Print the minimum value of the signal
print("Signal Min value:",s.DateCalMin())

Let's take a look at the running effect. You can see the result of applying 5-point moving average filtering to the original data (the blue line represents the original waveform, and the red line represents the filtered waveform):

5
5 0

To prevent anyone from instantiating objects directly from our interface classes, we can use the following code to raise a NotImplementedError exception when a method in the interface is called directly:

# Define the data processing interface
class DateProcessInterface(object):
    def __init__(self,DateList:List[int],FilterLength:int):
        '''
        Initialization method
        :param DateList: Data list
        :param FilterLength: Number of points to apply data filtering to
        '''
        raise NotImplementedError

3. Implement interfaces using Abstract Base Classes (ABCs)

In Python programming, Abstract Base Classes (ABCs for short) are an extremely useful tool for defining interfaces and standardizing the behavior of classes. Abstract base classes provide a mechanism that ensures subclasses implement specific methods and properties.

An abstract base class, which is also a type of class, needs to be defined using the class keyword. It differs from an ordinary class in two aspects:

In Python, the abc module can be used to define abstract base classes. When the above DateProcessInterface adopts an abstract base class, the sample code is as follows:

from abc import ABCMeta, abstractmethod
# Use an abstract base class to define the data processing interface
class DateProcessInterface(metaclass=ABCMeta):
    def __init__(self,DateList:List[int],FilterLength:int):
        '''
        Initialization method
        :param DateList: Data list
        :param FilterLength: Number of points to apply data filtering to
        '''
        pass

    @abstractmethod
    def DateFilter(self)->List:
        '''
        Abstract method, data filtering
        :return: List
        '''
        pass

    @abstractmethod
    def DateCalMax(self)->int:
        '''
        Abstract method, calculate the maximum value of the data
        :return: int
        '''
        pass

    @abstractmethod
    def DateCalMin(self)->int:
        '''
        Abstract method, calculate the minimum value
        :return: int
        '''
        pass

Here, we first need to pass the `metaclass` keyword argument to the interface class. This keyword involves knowledge points related to metaclass programming, which we will not introduce in detail. You only need to know that by assigning the `ABCMeta` metaclass, your class can be made into an abstract base class. Then, the decorator `@abstractmethod` is used to mark methods as abstract, which specifies that any subclass of this class must implement these methods.

Specifically, methods decorated with @abstractmethod must meet the following two requirements:

@abstractmethod can also annotate static methods, class methods, and properties — you only need to ensure that this annotation is placed immediately before the method definition.

class A(metaclass=ABCMeta):
    @property
    @abstractmethod
    def name(self):
        pass

    @name.setter
    @abstractmethod
    def name(self, value):
        pass

    @classmethod
    @abstractmethod
    def method1(cls):
        pass

    @staticmethod
    @abstractmethod
    def method2():
        pass

Abstract base classes can also be used for type checking with the isinstance () and issubclass () functions. For example:

print(issubclass(DateProcessClass, DateProcessInterface))
print(isinstance(DateProcessClass, DateProcessInterface))
The most beginner-friendly Object Oriented programming tutorial on the entire network: 50 Python function methods and interfaces - Interfaces and Abstract Base Classes