Technology Sharing

The most suitable introductory object-oriented programming tutorial on the entire network: Python implementation of 14 classes and objects - static methods and class methods of a class, can you tell them apart?

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

The most suitable introductory object-oriented programming tutorial on the entire network: Python implementation of 14 classes and objects - static methods and class methods of a class, can you tell them apart?

Summary:

This article mainly introduces class methods and static methods in classes and objects in Python, as well as their definitions, characteristics, application scenarios, and usage methods, and compares the two.

Original link:

FreakStudio's Blog

Previous recommendations:

This may be the most suitable introductory object-oriented programming tutorial on the entire Internet: Python implementation - a must-read for embedded enthusiasts!

The most suitable object-oriented programming tutorial on the entire network: 00 Introduction to Object-Oriented Design Methods

The most suitable object-oriented programming tutorial for beginners on the entire network: 01 Basic concepts of object-oriented programming

The most suitable object-oriented programming tutorial on the entire network: 02 Python implementation of classes and objects-using Python to create classes

The most suitable object-oriented programming tutorial on the entire network: 03 Python implementation of classes and objects-adding attributes to custom classes

The most suitable object-oriented programming tutorial for beginners on the entire network: 04 Python implementation of classes and objects - adding methods to custom classes

The most suitable object-oriented programming tutorial on the entire network: 05 Python implementation of classes and objects-PyCharm code tags

The most suitable object-oriented programming tutorial for beginners on the entire network: 06 Python implementation of classes and objects - data encapsulation of custom classes

The most suitable object-oriented programming tutorial on the entire network: 07 Python implementation of classes and objects - type annotations

The most suitable object-oriented programming tutorial on the entire network: Python implementation of 08 classes and objects - @property decorator

The most suitable object-oriented programming tutorial on the entire network: 09 Python implementation of classes and objects-the relationship between classes

The most suitable object-oriented programming tutorial on the entire network: Python implementation of 10 classes and objects - class inheritance and Liskov substitution principle

The most suitable object-oriented programming tutorial for beginners on the entire network: Python implementation of 11 classes and objects - subclasses calling parent class methods

The most suitable object-oriented programming tutorial on the entire network: Python implementation of 12 classes and objects - Python uses the logging module to output program running logs

The most suitable object-oriented programming tutorial on the entire network: Python implementation of 13 classes and objects - installation and use of Sourcetrail, a visual code reading tool

More exciting content to watch:

Brief Analysis of CM3 Debugging System

After half a month of hard work, a summary of the embedded technology stack is released

The secrets of winning the competition: 05 How to divide the technical work and learning content of the national award team in the electronic computer competition

Competition winning martial arts secrets: 04 Electronics competition embedded development quick must-read guide

The secrets of winning a competition: 03 Good creative selection - the most necessary prerequisite for winning a national award

Competition winning martial arts secrets: 02 National Award Secrets - A quick guide to college students' computer competitions, a must-read for beginners

Martial Arts Secrets for Winning Competitions: 01 How do you view the phenomena of “rolling”, “old projects inherited from ancestors” and “finding connections” in contemporary college student competitions?

Competition-winning martial arts secrets: 00 Subject competitions - a topic that engineering students cannot avoid, how much do you know?

The "Martial Arts Secrets" of electronic computer competitions - electrical competitions, optoelectronic design competitions, computer design competitions, embedded chip and system design competitions, everything you want is here!

Documentation and code acquisition:

You can visit the following link to download the document:

https://github.com/leezisheng/Doc

image

This document mainly introduces how to use Python for object-oriented programming, and requires readers to have a basic understanding of Python syntax and MCU 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. It uses common serial port data transmission and reception, data processing, dynamic graph drawing, etc. of host and slave computers as application examples, and uses Sourcetrail code software to visualize the code for easy understanding by readers.

The relevant sample code acquisition link is as follows:https://github.com/leezisheng/Python-OOP-Demo

text

Static methods

Taking the SensorClass class as an example, the methods defined in the class, such as InitSensor, StartSensor, StopSensor, etc., areObject Methods, which means that these methods are messages sent to the object and call the properties in the object.In fact, not all methods we write in a class need to be object methods. Some methods in a class do not need to call object properties. For example, in the InitSensor method, we may need to determine whether the current COM port exists. Obviously, this method has nothing to do with the sensor object.

For another example, we define a "Triangle" class, which constructs a triangle by passing in three side lengths, and provides methods for calculating the perimeter and area. However, the three side lengths passed in may not necessarily construct a triangle object, so we can first write a method to verify whether the three side lengths can form a triangle. This method is obviously not an object method, because the triangle object has not been created when this method is called (because we don't know whether the three sides can form a triangle), so this method belongs to the triangle class but not to the triangle object. We can useStatic methodsTo solve this type of problem, the code is as follows.

@staticmethod
    _# 判断传感器ID号是否正确:这里判断ID号是否在0到99之间_
    def IsTrueID(id:int = 0):
        if id >= 0 and id <= 99:
            return True
        else:
            return False
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Static methods are actually the functions we have learned. The only difference between them is that static methods are defined in the class space (class namespace), while functions are defined in the space where the program is located (global namespace). Static methods do not have special parameters such as self and cls, so the Python interpreter will not bind any class or object to the parameters it contains. Because of this, no class attributes or class methods can be called in the static methods of a class. Here we define the IsPort static method to determine whether the sensor ID number is correct. Static methods need to be modified with @staticmethod. Static methods can be called using either class names or class objects, for example:

_    # 设置ID号_
    id = 1
_    # 判断ID号是否符合格式_
    if SensorClass.IsTrueID(id):
        s = SensorClass()
    else:
        print("Sensor Init False")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

image

Class Methods

Similar to static methods, Python can also define class methods in classes. The first parameter of a class method is named cls, which represents an object of information related to the current class (the class itself is also an object, and is sometimes called the class metadata object). Through this parameter, we can obtain information related to the class and create an object of the class. Python will automatically bind the class itself to the cls parameter (note that it is not the class object that is bound). In other words, when calling a class method, we do not need to explicitly pass in the cls parameter.

Class methods need to be modified with the @classmethod modifier. We define the class method MasterInfo in MasterClass. The sample code is as follows:

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

print(MasterClass.MasterInfo())
  • 1
  • 2
  • 3
  • 4
  • 5

image

insert image description here