Python study notes | 2 Advanced functions

Contents of this chapter: Introduction to advanced knowledge of functions in Python, including multiple return values ​​of functions, various parameter passing methods of functions, anonymous functions, etc.

All relevant codes can be viewed at https://github.com/hzyao/Python-Cookbook .
If you are interested, you can also follow my public account. Xiaobai wants to know , thank you! ! !

It’s wonderful to learn and practice at the same time, and to discover in time! It may taste better if eaten together!

By the way, let me ask again, how many people like me miss R when they click on Python!

Function advanced

1 Multiple return values ​​of functions

If a function wants to have multiple return values, we only need to write multiple variables in the corresponding order according to the order of the return values. The variables are separated by commas to support different types of data return.

# 使用多个变量接收多个返回值
def multi_return():
    return 6, "xmy", True

x, y, z = multi_return()
print(x)
print(y)
print(z)

2 Various ways of passing parameters to functions

Due to different usage methods, the common usage methods of function parameters can be divided into 4 types:

  • Positional parameters
  • keyword arguments
  • Default parameters
  • variable length parameters

2.1 Position parameters

Positional parameters: When calling a function, parameters are passed according to the parameter position defined by the function .

Note: The order and number of parameters passed must be consistent with the parameters defined .

# 位置参数
def test_func(name, age, gender):
    print(f"姓名:{
      
      name}, 年龄:{
      
      age}, 性别:{
      
      gender}")

test_func("xmy", "17", "male")

2.2 Keyword parameters

Keyword parameters: Parameters are passed in the form of **"key=value"** when the function is called.

Function: It can make the function clearer and easier to use, while also clearing the order of parameters.

Note: When a function is called, if there are positional parameters, the positional parameters must be in front of the keyword parameters, but there is no order between keyword parameters.

# 关键字参数
def test_func(name, age, gender):
    print(f"姓名:{
      
      name}, 年龄:{
      
      age}, 性别:{
      
      gender}")

test_func("xmy", gender="male", age="17") # 可以与关键字参数混用,且可不按照参数定义顺序

2.3 Default parameters

Default parameters: Also called default parameters, they are used to define functions and provide default values ​​for parameters. The value of the default parameter does not need to be passed in when calling the function.

Function: When no parameters are passed when calling a function, the value corresponding to the default parameter will be used by default; if a value is passed in for the default parameter, the default value of the default parameter will be modified.

Note: All positional parameters must appear before the default parameters , including function definitions and calls, which means the default parameters must be defined at the end.

# 缺省参数
def test_func(name, age, gender="male"):
    print(f"姓名:{
      
      name}, 年龄:{
      
      age}, 性别:{
      
      gender}")

test_func("xmy", "17")
test_func("run", 18, gender="female")

2.4 Indefinite length parameters

Indefinite length parameters: Indefinite length parameters are also called variable parameters and are used in scenarios where it is not certain how many parameters (including no parameters) will be passed when calling.

Function: If you are not sure about the number of parameters when calling a function, you can use variable length parameters.

Type of variable length parameter:

  1. Positional passing: Mark *a formal parameter and accept parameters in the form of a tuple , usually named args.
  2. Keyword passing: **Mark a formal parameter and accept the parameters in the form of a dictionary , usually named kwargs.
# 不定长参数
## 位置传递
def test_func(*args):
    print(f"args参数类型是:{
      
      type(args)},内容是{
      
      args}")

test_func(666, "xmy")

## 关键字传递
def test_func(**kwargs):
    print(f"kwargs参数类型是:{
      
      type(kwargs)},内容是{
      
      kwargs}")

test_func(num=666, name="xmy")

3 Anonymous functions

3.1 Functions passed as parameters

In the previous studies, the functions we have been using accept data as parameters, such as numbers, strings, dictionaries, lists, tuples, etc.

In fact, the function itself can also be passed into another function as a parameter for use!

Function: transfer of calculation logic, not data . Any logic can be defined by yourself and passed in as a function.

# 函数作为参数传递
## 定义一个函数,接受另一个函数作为参数传入
def test_func(compute):
    result = compute(1, 2)
    print(type(compute))
    print(result)

## 定义一个函数,即将作为参数传入另一个函数
def compute(x, y):
    return x + y

## 调用并传入函数
test_func(compute)

3.2 lambda anonymous function

In function definition:

  • def, you can define a function with a name
  • lambda, you can define anonymous functions ( no names )

A function with a name can be used repeatedly based on the name ; an anonymous function without a name can only be used temporarily once .

Anonymous function definition syntax:lambda 传入参数:函数体

  • lambdais a keyword, indicating the definition of an anonymous function;
  • Pass in parameters, indicating the formal parameters of the anonymous function, such as: x, yindicating receiving 2 formal parameters;
  • The function body is the execution logic of the function. Note: You can only write one line , and you cannot write multiple lines of code. If you need multiple lines, you should use defa function defined with a name.
# lambda 匿名函数
## 定义一个函数,接受另一个函数作为参数传入
def test_func(any):
    result = any(1, 2)
    print(result)

## 通过 lambda 匿名函数形式,将匿名函数作为参数传入
test_func(lambda x, y: x + y)

# 以上使用 def 和 lambda 定义的函数功能完全一致,只不过 lambda 定义的函数是匿名的,无法二次使用。

Guess you like

Origin blog.csdn.net/weixin_43843918/article/details/131465595