Location>code7788 >text

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 46 Python Function Methods and Interfaces - Functions and Event-Driven Frameworks

Popularity:795 ℃/2024-09-09 22:56:35

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 46 Python Function Methods and Interfaces - Functions and Event-Driven Frameworks

image

Abstracts:

Functions are first-class citizens in Python, a reusable block of code used to encapsulate specific logic; event-driven framework is a programming paradigm that shifts the flow of control of a program to external events, such as user input, system messages, and so on, and it event-driven frameworks can use functions as the processing logic for events.

Link to original article:

FreakStudio's Blog

Past Recommendations:

You're learning embedded and you don't know how to be object oriented?

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 00 Introduction to Object-Oriented Design Methods

The network's most suitable for the introduction of object-oriented programming tutorials: 01 Basic Concepts of Object-Oriented Programming

The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 02 Python Implementations of Classes and Objects - Creating Classes with Python

The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 03 Python Implementations of Classes and Objects - Adding Attributes to Custom Classes

The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 04 Python Implementation of Classes and Objects - Adding Methods to Custom Classes

The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 05 Python Implementation of Classes and Objects - PyCharm Code Tags

The best object-oriented programming tutorials on the net for getting started: 06 Python implementation of classes and objects - data encapsulation of custom classes

The best object-oriented programming tutorial on the net for getting started: 07 Python implementation of classes and objects - type annotations

The best object-oriented programming tutorials on the net for getting started: 08 Python implementations of classes and objects - @property decorator

The best object-oriented programming tutorials on the net for getting started: 09 Python implementation of classes and objects - the relationship between classes

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 10 Python Implementations of Classes and Objects - Class Inheritance and Richter's Replacement Principle

The best object-oriented programming tutorials on the net for getting started: 11 Python implementation of classes and objects - subclasses call parent class methods

The network's most suitable for the introduction of object-oriented programming tutorials: 12 classes and objects of the Python implementation - Python using the logging module to output the program running logs

The network's most suitable for the introduction of object-oriented programming tutorials: 13 classes and objects of the Python implementation - visual reading code artifacts Sourcetrail's installation use

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 14 Python Implementations of Classes and Objects - Static Methods and Class Methods for Classes

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 15 Python Implementations of Classes and Objects - __slots__ Magic Methods

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 16 Python Implementations of Classes and Objects - Polymorphism, Method Overriding, and the Principle of Open-Close

The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 17 Python Implementations of Classes and Objects - Duck Types and "file-like objects"

The network's most suitable for the introduction of object-oriented programming tutorials: 18 classes and objects Python implementation - multiple inheritance and PyQtGraph serial data plotting graphs

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 19 Python Implementations of Classes and Objects - Using PyCharm to Automatically Generate File Annotations and Function Annotations

The best object-oriented programming tutorials on the web for getting started: 20 Python implementation of classes and objects - Combinatorial relationship implementation and CSV file saving

The best introductory object-oriented programming tutorials on the net: 21 Python implementation of classes and objects - Organization of multiple files: modulemodule and packagepackage

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 22 Python Implementations of Classes and Objects - Exceptions and Syntax Errors

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 23 Python Implementation of Classes and Objects - Throwing Exceptions

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 24 Python Implementations of Classes and Objects - Exception Catching and Handling

The best object-oriented programming tutorials on the web for getting started: 25 Python implementation of classes and objects - Python to determine the type of input data

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 26 Python Implementations of Classes and Objects - Context Managers and with Statements

The best introductory object-oriented programming tutorials on the web: 27 Python implementation of classes and objects - Exception hierarchy and custom exception class implementation in Python

The best object-oriented programming tutorials on the net for getting started: 28 Python implementations of classes and objects - Python programming principles, philosophies and norms in a big summary

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 29 Python Implementations of Classes and Objects - Assertions and Defensive Programming and Use of the help Function

The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 30 Python's Built-In Data Types - the root class of object

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 31 Python's Built-In Data Types - Object Object and Type Type

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 32 Python's Built-in Data Types - Class Class and Instance Instance

The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 33 Python's Built-In Data Types - The Relationship Between the Object Object and the Type Type

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 34 Python's Built-In Data Types - Python's Common Compound Data Types: Tuples and Named Tuples

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 35 Python's Built-In Data Types - Document Strings and the __doc__ Attribute

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 36 Python's Built-In Data Types - Dictionaries

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 37 Python's Common Composite Data Types - Lists and List Derivatives

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 38 Python's Common Composite Data Types - Using Lists to Implement Stacks, Queues, and Double-Ended Queues

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 39 Python Common Composite Data Types - Collections

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 40 Python's Common Compound Data Types - Enumeration and Use of the enum Module

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 41 Python's Common Composite Data Types - Queues (FIFO, LIFO, Priority Queue, Double-Ended Queue, and Ring Queue)

The best introductory object-oriented programming tutorials on the web: 42 Python commonly used composite data types-collections container data type

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 43 Python's Common Composite Data Types - Extended Built-In Data Types

The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 44 Python Built-In Functions and Magic Methods - Magic Methods for Rewriting Built-In Types

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 45 Python Implementations of Common Data Structures - Chain Tables, Trees, Hash Tables, Graphs, and Heaps

More highlights to watch:

Accelerating Your Python: A Quick Guide to Python Parallel Computing

Understanding CM3 MCU Debugging Principles in One Article

Liver half a month, embedded technology stack summary out of the big

The "Secrets of the Martial Arts" of the Computer Competition

A MicroPython open source project collection: awesome-micropython, including all aspects of Micropython tool library

Avnet ZUBoard 1CG Development Board - A New Choice for Deep Learning

SenseCraft Deploys Models to Grove Vision AI V2 Image Processing Module

Documentation and code acquisition:

The following link can be accessed to download the document:

/leezisheng/Doc

image

This document mainly introduces how to use Python for object-oriented programming, which 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, with common serial port data sending and receiving, data processing, and dynamic graph drawing as application examples for both the host computer and the downstream computer, while using Sourcetrail code software to visualize and read the code for readers' easy understanding.

The link to get the relevant sample code is below:/leezisheng/Python-OOP-Demo

main body (of a book)

function (math.)

A function is a named block of code that takes zero or more input arguments and returns an output value when it is run. In Python, functions are not only objects, but also First-Class Objects, which is one of the characteristics of Python functions. Functions are objects that can be assigned to a variable, added as elements to a collection, passed as arguments to other functions, and used as the return value of a function, all of which are unique to First-Class Objects.

image

Simply put, functions can be used in Python in any way you want, just like normal variables. This includes assigning values, and using them as arguments and return values for other functions. This makes it easy to write code for higher-order functions and closures. In other languages that use object-oriented design (such as C++), you need to use function pointers to do this.

In many cases, we need to pass functions as arguments to another function. The most typical example is the event-driven programming model, theThe so-called event-driven programming model is different from the original programming model of executing each function in turn, and its basic processing idea is to pre-design a program formed by an event loop, which constantly checks the information to be processed at present, and executes a triggering function to carry out the necessary processing according to the information to be processed.Where this external information may come from a file in a directory folder, it may come from a keyboard or mouse action, or it may be a time event.

From an event perspective, the basic structure of an event driver consists of an event collector, an event sender and an event handler. The event collector is exclusively responsible for collecting all events, including those from the user (e.g., mouse, keyboard events, etc.), from the hardware (e.g., clock events, etc.), and from software (e.g., the operating system, the application program itself, etc.). The event sender is responsible for distributing the events collected by the collector to the target object. The event handler does the specific event response work, which is often not fully defined until the implementation phase.In the event handler generally need to pass a registered callback function in advance, after the callback function is registered, the program will continue to execute the later statements, and the callback function will be called asynchronously after the corresponding event is generated.

A function is an object that has three common properties of the object model: id, type, and value. In the following code, we create an average filter function to realize three cycles of the sensor sampling value to calculate the average value, in the code, DataList is a global variable, it is used to record the sampling value of the FileterLength cycles, AverageFilter(value) is a filter function, and its input is the newly collected data, in the function. In the function, first shift the data in DataList[], and save the newly collected data into the last element of DataList[], meanwhile calculate the sum of 10 data in DataList[], and finally return the average value of the sum of FileterLength data. The sample code is as follows:

_# Global variable to record three cycles of sampling values _#
FileterLength = 3
DataList = [0] * FileterLength
def AverageFilter(value).
    '''
    Average filter function to calculate the average value of the sensor samples in three cycles.
    :param value: current sample value
    :return: Filtered sensor value
    '''
    global DataList
    _# Temporary variable storing the sum of the data in the list.
    sum = 0
    for i in range(FilterLength-1): _# Implement list shift operation _#.
        _# Implement shift operations for the list _
        DataList[i] = DataList[i+1]
        _# Implement list summing _
        sum += DataList[i]
    DataList[FileterLength-1] = value
    sum += DataList[FileterLength-1] = value
    average = sum / len(DataList)
    return average

Let's first access the basic properties of this function:

print(id(AverageFilter))
print(type(AverageFilter))
print(AverageFilter)

The results of the run are as follows:

image

We can add custom properties to functions and access them:

 = ("The average value filter function realizes the calculation of the average value "
                             "of the sensor sample value for three periods")
print()

The results of the run are as follows:

image

Event Driven Framework Timer

Next we use an event-driven framework timer example to better illustrate the function as a parameter can be passed to another function related applications. The sample code is shown below:

import datetime
import time

_# Define the timed event class _#
class TimedEvent.

    def __init__(self, endtime, callback).
        '''
        Initialization method, storing endtime and callback.
        :param endtime: the time to wait before the callback is executed.
        :param callback: the callback function, i.e. the function that is called when it reaches the execution time.
        '''
         = endtime
         = callback

    def ready(self).
        '''
        Determine if the event has reached the right time to be executed.
        :return.
        '''
        return <= ()

_# Define timer class, polling detection to implement task scheduling _
class Timer.
    def __init__(self).
        '''
        Initialization method, define a list of events to store.
        '''
         = []

    def call_after(self, delay, callback).
        '''
        Add a new event
        :param delay: number of seconds to wait before executing the callback method
        :param callback: callback method
                         The callback function should take one parameter: the timer to execute the call
        :return.
        '''
        end_time = (() +
                    (seconds=delay))
        (TimedEvent(end_time, callback))

    def run(self).
        '''
        Polling detection and execution of the callback function that reaches the execution time
        :return.
        '''
        _# Polling detection, execute callback function that reaches the execution time _
        while True: _# Use a generator expression.
            _# Use a generator expression to filter out events whose time has come _# while True.
            ready_events = (e for e in if ())
            _# Execute in order _
            for event in ready_events: (self)
                (self)
                _# Remove completed tasks when execution is complete _
                (event)
            _# Sleep for 0.5 seconds during each iteration to prevent the system from crashing _# for event in ready_events: (self) _# Remove completed tasks after execution is complete _# (event)
            (0.5)

Below, we write a couple of callback functions to test it:

def format_time(message, *args).
    '''
    Add the current time to the message using the format method of the string, and specify the variable arguments
    :param message: receive any number of positional arguments
    :param args: A sequence of positional arguments to be processed in the function.
    :return: None
    '''
    _# The current time, in the format: hour-minute-second_.
    now = ().strftime("%I:%M:%S")
    _# Formatting print arguments _
    print((*args, now=now))

_# Callback function: task one_
def Task_One(timer):
    format_time("{now}: Called Task One")

_# Callback function: Task Two _
def Task_Two(timer): format_time("{now}: Called Task One") _# Callback function: Task Two_.
    format_time("{now}: Called Task Two")

_# Callback function: Task Three
def Task_Three(timer): format_time("{now}: Called Task Two") _# Callback function: Task Three_.
    format_time("{now}: Called Task Three")

_# Create a timer object _
timer = Timer()
_# Add the callback function _
timer.call_after(1, Task_One)
timer.call_after(2, Task_One)
timer.call_after(2, Task_Two)
timer.call_after(4, Task_Two)
timer.call_after(3, Task_Three)
timer.call_after(6, Task_Three)
_# Start running the timer _
format_time("{now}: Starting")
()

The results of the run are as follows, and you can see that upon reaching their respective execution times, each event simply outputs the current time and a short message telling us which callback method was called.

image

In fact, the methods of the class can also be used as callback functions, the sample code is as follows

_# Define class _
class Repeater.
    def __init__(self).
         = 0
    def repeater(self, timer): = 0
        '''
        Create a timer task in the function
        :param timer: timer
        :return: None
        '''
        format_time("{now}: repeat {0}", )
         += 1
        _# Class methods can also be used as callback functions _
        timer.call_after(5, )

_# Create a timer object _
timer = Timer()
repeater = Repeater()
_# Add callback function, class method _
timer.call_after(5, )
_# Start running the timer _
format_time("{now}: Starting")
()

The results of the run are as follows:

image

We can't tell from the run results that we can add new events to the timer from the callback function that is currently running. Then create a timer and add several events that are called after different times.

Format function

In Python, format() is a built-in function for formatting strings. format() provides a flexible way to insert variables into strings and control the format in which they are displayed.

Its syntax is as follows:

format(value, format_spec)

where the parameters are described as follows:

  • value: the value to be formatted; format_spec: the formatting specification, used to specify how the value should be displayed.
  • The format() function returns a formatted string.

It replaces the old % with {} and :. The format function can take an unlimited number of arguments, and the positions can be out of order. The example code is as follows:

_# Do not set the specified position, in the default order _
print("{} {}".format("hello", "world"))
_# Set the specified position _
print("{0} {1}".format("hello", "world"))
_# set the specified position _# print("{0} {1}".format("hello," "world"))
print("{1} {0} {1}".format("hello", "world"))

The output is as follows:

image

image