Labs / Python OOP

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

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

Contents
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

Abstract:

In Python, a function can accept multiple types of parameters, including positional parameters, default parameters, variable parameters and keyword parameters. Understanding these parameter types is of great importance for writing flexible and maintainable code.

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 on the entire 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 Across the Network: 26 Python Implementation of Classes and Objects - Context Managers and the with Statement

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 27 Python Implementation of Classes and Objects - Exception Hierarchy and Custom Exception Class Implementation 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 Tutorial 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

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 4

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, 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 to facilitate readers' understanding.

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

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

Body Text

Positional Arguments

Positional arguments are the most common type of parameter, whose values are determined by the position when calling a function. The order of parameters in a function definition determines their corresponding relationship during function calls. For example:

def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet("Alice", 30)
# Output: Hello Alice, you are 30 years old.

In this example, name and age are positional parameters. When the greet function is called, "Alice" corresponds to name, and 30 corresponds to age.

Keyword Arguments

Keyword arguments allow you to explicitly specify the name of an argument when calling a function. They can be mixed with positional arguments, but keyword arguments must be provided after positional arguments.

def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet(name="David", age=28)
# Output: Hello David, you are 28 years old.

In this example, name and age are passed as keyword arguments. This improves code readability and allows you to specify arguments in any order when calling a function.

Default Arguments

Default parameters allow you to provide default values for parameters when defining a function. If these parameters are not passed when calling the function, the default values will be used. For example:

def greet(name, age=25):
    print(f"Hello {name}, you are {age} years old.")

greet("Bob")
# Output: Hello Bob, you are 25 years old.

greet("Charlie", 40)
# Output: Hello Charlie, you are 40 years old.

In this example, age parameter has a default value of 25. If you call the greet function without providing a value for age, it will use this default value.

variadic parameter

In Python, in addition to the traditional positional arguments, keyword arguments and default arguments, there are also two methods: variable-length arguments and variable-length keyword arguments, which will be explained next. In the following example, we define a function that can print the two strings passed into the function:

def print_str(first, second):
    print(first, second)

print_str("hello", "world")

If you call it with one argument, like print_str ("hello"), an exception will definitely be thrown. If we are not sure about the number of strings to pass in advance, we can use Python variable arguments to implement it. Variable arguments refer to parameters that can accept any number of arguments. In Python, variable arguments can be defined by adding an asterisk * before the parameter name, so that the function can accept any number of positional arguments.

When defining a function, variable arguments are usually accepted with *args, where the * is mandatory, and args can be replaced with other names, but it is customary to use args for representation. After being passed into the function, variable arguments are encapsulated into a tuple for use. Therefore, inside the function, we can manipulate the arguments by operating on the tuple. The sample code is as follows:

def print_str(first_str, *args):
    print(type(args))
    print(args)
    print(first_str)
    for n in args:
        print(n)

print_str("hello", "world","i","am","coming")

The following are the operation results:

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

If a list or tuple has already been defined outside a function and you want to call it with variable arguments, you can also use the * + variable name form for invocation (this usage is somewhat similar to pointers in the C language). At this point, when the function is called, the passed tuple parameter will be unpacked, with each element automatically serving as a positional argument of the function. An example is as follows:

def print_str(first_str, *args):
    print(type(args))
    print(args)
    print(first_str)
    for n in args:
        print(n)

l=["world","i","am","coming"]
print_str("hello",*l)

The running results are as follows:

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

Variable arguments allow you to pass zero or any number of arguments, which are automatically assembled into a tuple when the function is called, while variable keyword arguments allow you to pass zero or any number of arguments with parameter names, which are automatically assembled into a dict inside the function.

Variable keyword arguments are identified by kwargs, which are used to extend the functionality of a function. For example, when we want to implement user registration, there are required fields and optional fields, and these optional fields can be accepted using variable keyword arguments.

The sample code is as follows:

def register(name, email, **kwargs):
    print("name: {}, age: {}, others: {}".format(name, email, kwargs))
    for i in kwargs:
        print(str(i)+":"+kwargs[i])

register("demon", "1@1.com", addr="shanghai",gender="male", birthday="2022-03-31")

The running results are as follows:

101.com 2022-03-31 0

For keyword arguments, the caller of a function can pass any number of unrestricted keyword arguments. As for which ones are actually passed, it is necessary to check them via kwargs inside the function. If you want to restrict the names of keyword arguments, you can use named keyword arguments, for example, only accepting addr and gender as keyword arguments. A function defined in this way is as follows:

def register(name, email,*,addr,gender):
    print("name: {}, age: {}, addr: {}, gender: {}".format(name, email, addr,gender))

register("demon", "1@1.com", addr="shanghai",gender="male")

Different from the keyword argument **kw, named keyword arguments require a special separator, and the arguments following the separator are regarded as named keyword arguments. Named keyword arguments must be passed with their argument names, which is different from positional arguments. When defining a function, the order of parameters must be: required (positional) parameters -> default parameters -> variable positional parameters -> variable keyword parameters.

347622978