Labs / Python OOP

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 14 Python Implementation of Classes and Objects – Can You Tell the Difference Between Static Methods and Class Methods of a Class?

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

Contents

Abstract:

This paper mainly introduces the class methods and static methods in classes and objects of Python, as well as their definitions, features, application scenarios and usage methods, and makes a comparison between the two.

FreakStudio's Blog

Previous Recommendations:

You who are learning 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 Tags

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 06 Python Implementation of Classes and Objects - Data Encapsulation of Custom Classes

The most beginner-friendly Object Oriented programming tutorial on 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

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 grinding, the ultimate 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 74 19 1.1

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

static method

Taking the SensorClass class as an example, the methods defined in the class such as InitSensor, StartSensor, and StopSensor are all instance methods; that is to say, these methods are messages sent to an object and all invoke the properties within the object. In practice, not all methods we write in a class need to be instance methods. There are some methods in a class that do not require accessing object properties. For instance, in the InitSensor method, we may need to check whether the current COM port exists, and obviously this method has nothing to do with the sensor object.

As another example, when we define a "Triangle" class, which constructs a triangle by taking three side lengths and provides methods to calculate its perimeter and area, the three given side lengths may not necessarily form a valid triangle object. Therefore, we can first write a method to verify whether the three side lengths can form a triangle. Obviously, this method is not an instance method, because when we call this method, the triangle object has not been created yet (since we do not even know whether the three sides can form a triangle). Thus, this method belongs to the Triangle class rather than to any specific triangle object.We can use static methods to solve this type of problem, and the code is shown below.

    @staticmethod
    # Check whether the sensor ID is valid: here, check whether the ID is between 0 and 99
    def IsTrueID(id:int = 0):
        if id >= 0 and id <= 99:
            return True
        else:
            return False

A static method is essentially the function we have learned. Its only difference from a function is that a static method is defined in the class scope (the class namespace), whereas a function is defined in the scope where the program resides (the global namespace). A static method has no special parameters such as self or cls, so the Python interpreter will not perform any class or object binding on the parameters it contains. Precisely because of this, no class attributes or class methods can be called within a class's static method.Here we define the static method IsPort to determine whether the sensor ID is valid. A static method needs to be decorated with @staticmethod. To call a static method, you can use either the class name or a class object, for example:

    # Set the ID
    id = 1
    # Check whether the ID matches the format
    if SensorClass.IsTrueID(id):
        s = SensorClass()
    else:
        print("Sensor Init False")
6

class method

Similar to static methods, Python also allows defining class methods within a class. The first parameter of a class method is conventionally named cls, which refers to an object containing information related to the current class (the class itself is also an object, sometimes referred to as the class's metadata object). Through this parameter, we can obtain class-related information and instantiate objects of the class, and Python automatically binds the class itself to the cls parameter (note that what is bound is not the class object). In other words, when calling a class method, we do not need to explicitly pass a value to the cls parameter.

Class methods need to be decorated with the @classmethod decorator. The following is the sample code for defining the class method MasterInfo in MasterClass:

@classmethod
    def MasterInfo(cls):
        print("Info : "+str(cls))

print(MasterClass.MasterInfo())
The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 14 Python Implementation of Classes and Objects – Can You Tell the Difference Between Static Methods and Class Methods of a Class?
347622978