Proficient in Python functions and have an in-depth understanding of *args and **kwargs

This article will help you master Python functions and gain an in-depth understanding *argsof and **kwargs.

Search and follow "Python Learning and Research Basecamp" on WeChat, join the reader group, and share more exciting things

picture

1. Make the code cleaner and more flexible

picture

Imagine if you could create functions in Python that fit different scenarios without having to rewrite them every time. This is where the magic of *argsand **kwargs. It's like preparing a magic bag for the function that can hold as many parameters as you want - making the code cleaner and more flexible.

To help you better understand *argssums in Python **kwargs, let's show you what the code would look like without these concepts.

Here, this article shows a simple function simple_sumfor adding two numbers.

def simple_sum(a, b):
    return a + b

result = simple_sum(3, 7)
print(result)

Now, imagine if you want to create a function that adds three numbers. This function may eventually be rewritten as follows:

def simple_sum_three(a, b, c):
    return a + b + c

result_three = simple_sum_three(3, 7, 5)
print(result_three)

What if you want to add four, five or more numbers? Users would have to create new functions for each case, which is neither elegant nor flexible.

To solve this problem, there is a concept called "parameter packing", you can use symbols in the function definition statement *to convert one parameter into a super parameter, which can be used as a bag and hold/package the passed it when calling the function All values ​​are stored in a variable.

Likewise, symbols *can also be used to unpack data structures, depending on how it is used, and we will learn how to do this later in this article.

This article assumes that you are already familiar with creating functions in Python, have a basic understanding of regular (positional) arguments and keyword arguments, and know what tuples and dictionaries are in Python.

2. Use *argsparameter packaging

In Python, when you see an asterisk ( *) immediately preceding a parameter in a function definition, it signals parameter packing. This means that any number of arguments can be passed to the function and they will be neatly packed into a tuple. It's like having a magic bag for the function that allows it to adapt to different situations without having to constantly rewrite the function.

def magic_sum(*args):
    result = sum(args)
    return result

# 三个数字相加
result1 = magic_sum(3, 7, 5)
print("Result 1:", result1)  # 预期输出:15(3+7+5)

# 五个数字相加
result2 = magic_sum(1, 2, 3, 4, 5)
print("Result 2:", result2)  # 预期输出:15(1+2+3+4+5)

# 相加更多数字
result3 = magic_sum(10, 20, 30, 40, 50, 60)
print("Result 3:", result3)  # 预期输出:210(10+20+30+40+50+60)

In this example, magic_sumthe function uses *argsparameter packing. This function can be called with a different number of arguments, which will be neatly packed into a tuple for addition. In this case, the variable argsbecomes a tuple. It's like having a calculator that can handle any number of inputs without having to change its formulas.

3. Parameter unpacking

On the other hand, when calling a function, you can use an asterisk ( *) to indicate that you are unpacking a sequence of values ​​(tuple, list, set, string) and passing its elements as separate values. This approach is suitable for situations where you hold your data in a collection (for example: a tuple), but want to extract each value from the collection and pass it as a separate argument to a function.

def display_values(a, b, c):
    print("Value of a:", a)
    print("Value of b:", b)
    print("Value of c:", c)

# 解包一个元组并将其元素作为单独的值传递
tuple_values = (7, 14, 21)
display_values(*tuple_values) # 等同于 display_values(7, 14, 21)

You can use this method to extract values ​​from multiple collection type data:

def display_values(a, b, c):
    print("Value of a:", a)
    print("Value of b:", b)
    print("Value of c:", c)

# 解包一个元组并将其元素作为单独的值传递
tuple_values = (7, 14, 21)
display_values(*tuple_values)  # 等同于 display_values(7, 14, 21)

# 解包一个列表
list_values = [30, 40, 50]
display_values(*list_values)  # 等同于 display_values(30, 40, 50)

# 解包一个字符串(每个字符成为单独的参数)
string_values = "XYZ"
display_values(*string_values)  # 等同于 display_values('X', 'Y', 'Z')

# 解包一个集合
set_values = {60, 70, 80}
display_values(*set_values)  # 顺序可能会有变化,等同于 display_values(60, 70, 80)

# 解包一个范围
range_values = range(3, 6)
display_values(*range_values)  # 等同于 display_values(3, 4, 5)

You can also change athe , b, in the function definition section to accept a variable number of arguments. Will be a tuple of all arguments passed. This can be understood as packaging and unpacking at the same time.cvaluesvalues

def display_values(*values): # 将数值打包到一个变量中。
    print("Values:", values)

# 解包一个元组并将其元素作为单独的值传递
tuple_values = (7, 14, 21)
display_values(*tuple_values)

4. Use **keyword parameter packaging

Next, this article will use the double asterisk ( **), an operator in Python that introduces the packing and unpacking of dictionaries. When a function parameter is **prefixed with " ", it indicates that the corresponding parameter should be a key-value pair, neatly packed into a dictionary. This is the same as packing of tuple arguments, but used when the function arguments are keyword arguments.

def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# 在函数调用中直接传递关键字参数
display_info(name='Alice', age=25, city='Wonderland')

5. Keyword parameter unpacking

Unpack the dictionary and pass its contents as separate keyword arguments to the function. This approach is useful when you have your data in a dictionary, but you want to extract each key-value pair from the dictionary and pass it as a separate keyword argument to a function:

def display_person_info(name, age, city):
    print("Name:", name)
    print("Age:", age)
    print("City:", city)

# 解包一个包含预期键值对的字典
person_info = {'name': 'Alice', 'age': 25, 'city': 'Wonderland'}
display_person_info(**person_info)

6. Use in combination *argswith**kwargs

Combine the power of *argsand **kwargsby treating them as variable-length positional argument lists and keyword argument lists respectively.

def display_information(*args, **kwargs):
    print("Positional Arguments (*args):")
    for arg in args:
        print(arg)

    print("\nKeyword Arguments (**kwargs):")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# 使用位置参数和关键字参数的混合调用函数
display_information(1, 'apple', name='Alice', age=25, city='Wonderland')

In this example, display_informationthe function receives *argsto handle any number of positional arguments and receives **kwargsto handle any number of keyword arguments. The function then prints each type of argument separately.

7. Unpack multiple times at one time

Another interesting feature in Python is the ability to perform multiple unpackings in a single function call.

def display_values(*args):
    for value in args:
        print(value)

# 在单个函数调用中进行多次解包
list_values = [1, 2, 3]
tuple_values = (4, 5, 6)
set_values = {7, 8, 9}

display_values(*list_values, *tuple_values, *set_values)

In this example, display_valuesthe function calls three different iterable types (list, tuple, and set) in a single line using multiple unpacking. During the function call, all values ​​are collected through multiple unpacking ( *list_values, *tuple_values, *set_values) and stored in a single argsparameter.

8. Notes on Naming Conventions

It is not necessary to name the parameters " args" or " kwargs", but many Python engineers do. It's like using a special word that everyone in the programming world understands. " args" is used for positional parameters and " kwargs" is used for keyword parameters.

Recommended book list

"Python from Beginner to Master (Micro Course Compiled Edition)"

"Python from Beginner to Master (Micro Course Compiled Edition)" uses easy-to-understand language and rich cases to introduce the programming knowledge and application skills of the Python language in detail. The book has 24 chapters in total, including Python development environment, variables and data types, expressions, program structures, sequences, dictionaries and sets, strings, regular expressions, functions, classes, modules, exception handling and program debugging, processes and threads , file operations, database operations, graphical interface programming, network programming, Web programming, web crawlers, data processing, etc. It also introduces multiple comprehensive practical projects in detail. Among them, Chapter 24 is about the online development of extended projects and is a purely online chapter. The book has a complete structure, combines knowledge points with examples, and is equipped with practical cases. It is highly operable. Most of the example source codes are given detailed annotations, so readers can learn easily and get started quickly. This book adopts the O2O teaching model, with offline and online collaboration. It is based on paper content and expands more value-for-money online content. Readers can quickly read, expand knowledge, and broaden their horizons by using WeChat on their mobile phones to scan. Get excess practical experience.

"Python from Beginner to Master (Micro Course Compiled Edition)" icon-default.png?t=N7T8https://item.jd.com/13524355.html

picture

Highlights

"Concise programming, 10 Python Itertools methods to help you get twice the result with half the effort"

"15 Must-Know Pandas Code Snippets to Help You Master Data Analysis"

"How to Choose a Python Dictionary: The Ultimate Guide to Mastering 6 Types!"

"Easy to play with Python, create stunning line charts in 5 steps"

"10 Data Type Tips in Python"

"Python's collection module, using data containers to process data collections"

Search and follow "Python Learning and Research Basecamp" on WeChat, join the reader group, and share more exciting things

Visit [IT Today’s Hot List] to discover daily technology hot spots

Guess you like

Origin blog.csdn.net/weixin_39915649/article/details/135401353