Zero-based entry python3.7-summary of basic knowledge (11) function upgrade

One. Function parameters

When defining a function, we determine the name and position of the parameter, and the interface definition of the function is completed. For the caller of a function, it is enough to know how to pass the correct parameters and what value the function will return. The complex logic inside the function is encapsulated, and the caller does not need to know.

two. Formal parameter

When the function is defined, the parameter in parentheses behind the function name is the formal parameter, referred to as "formal parameter".

def get_number_remainder(a, b):
    generate_list = list(range(a, b + 1))
    remainder_list = []
    for i in generate_list:
        if i % 5 != 0 and i % 3 != 0:
            remainder_list.append(i)
    return remainder_list

The a and b in the above code are formal parameters

three. Actual parameter

When calling a function, the parameter in parentheses behind the function name is called the actual parameter, which is the parameter given to the function by the caller of the function. Referred to as "real parameter"

a = get_number_remainder(200, 300)

four. How actual and formal parameters are passed

In python. According to the different types of actual parameters. Function transfer parameters can be divided into "value transfer parameters" and "reference transfer parameters are addresses"

  • Value transfer parameter: refers to the data whose actual parameter data type is immutable. E.g. String. digital. Tuple.
  • Address transfer parameter: refers to the variable data type of the actual parameter. E.g. List. dictionary.

Note: After the function parameter is passed, if the value of the formal parameter changes, it will not affect the actual parameter value; and after the function parameter continues to refer to the transfer, if the value of the formal parameter is changed, the actual parameter value will also change. As for why this underlying storage mechanism is related. The basic type stores the value. Reference type storage address. The mechanism of passing parameters will be explained later.

a = 100

def get_number(mag):
    mag = str(mag) + '-------这里改变了参数的值'
    print(mag)

get_number(a)
print(a)


100-------这里改变了参数的值
----------------------------
100

Obviously for the basic types, no matter how we operate the formal parameters, the actual parameters will not be affected.

a = {
    "name": "小王",
    "age": 28
}

def get_obj(obj):
    obj['name'] = "jack"
    print(obj)

get_obj(a)
print(a)

{'name': 'jack', 'age': 28}
{'name': 'jack', 'age': 28}

For reference types. After we change the value of the formal parameter, the actual parameter value will also change.

Fives. Position parameters (parameter pass)

This method of passing parameters is required. The position and number of actual parameters passed in when calling a function must correspond accordingly.

  • The number of actual and formal parameters must be consistent

    Example one

def get_data(a):
    print(a)

get_data(100, 200)

Traceback (most recent call last):
  File "/Users/apple/Documents/重要文件/python3/python21.py", line 15, in <module>
    get_data(100, 200)
TypeError: get_data() takes 1 positional argument but 2 were given

    Example 2

def get_data(a, b):
    print(a, b)

get_data(100)

Traceback (most recent call last):
  File "/Users/apple/Documents/重要文件/python3/python21.py", line 15, in <module>
    get_data(100)
TypeError: get_data() missing 1 required positional argument: 'b'

    Example three

def get_data(a, b):
    print(a, b)

get_data(100, 200)

100 200

The above code. Example 1: Pass one more parameter when the function is called. In the second example, one parameter was missing during the call. At this time, an exception will be thrown. Only Example 3 When the actual parameters and formal parameters are equal, the code executes normally and prints the result.

  • The position of actual and formal parameters must be consistent

1 An exception is thrown when the types of actual parameters and formal parameters are inconsistent

def get_data(a, b):
    print(100 + a)
    print("python" + b)

get_data("3.7", 100)

Traceback (most recent call last):
  File "/Users/apple/Documents/重要文件/python3/python21.py", line 16, in <module>
    get_data("3.7", 100)
  File "/Users/apple/Documents/重要文件/python3/python21.py", line 13, in get_data
    print(100 + a)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

From the above function we can clearly see that a should be a numeric type. b should be a string type. And when we call the function, we ensure that the number of parameters is always the same. However, the position of the parameter was changed, which caused an exception.

def get_data(a, b):
    print(100 + a)
    print("python" + b)

get_data(100, '3.7')

200
python3.7

At this time, when we exchanged the positions of the parameters, we also got the correct results. At the same time we can use the previous isinstance () to check whether our parameters match our type.

1 The results produced are not as expected


def get_data(a, b):
    d = a + 100 * b
    print(d)

get_data(120, 200)
get_data(200, 120)

# 正确结果
20120
------------------
# 错误结果
12200

When calling a function, if the positions of the specified actual parameters and formal parameters are inconsistent, but their data types are the same, the program will not throw an exception, but will cause the running result to be inconsistent with expectations

six. Keyword pass

Keyword parameters refer to the use of formal parameter names to determine input parameter values. When specifying the actual parameter of the function in this way, it is no longer necessary to exactly match the position of the formal parameter, as long as the parameter name is written correctly.

def get_data(a, b):
    d = a + 100 * b
    print(d)

#  关键字传参
get_data(a=120, b=200)
#   对位传参
get_data(120, 200)

20120
20120

We found that for a function, it is possible to use the parametric pass parameter or the keyword pass parameter when calling. However, it is clear that the keyword pass parameter solves the shortcomings of the bit pass parameter.

Can the parametric pass-through and keyword pass-through be used together? The answer is yes, see the following example

1. Example one

def get_data(a, b):
    d = a + 100 * b
    print(d)

#  关键字传参
get_data(120, b=200)

20120

2 Example 2

def get_data(a, b):
    d = a + 100 * b
    print(d)

#  关键字传参
get_data(a =120, 200)

  File "/Users/apple/Documents/重要文件/python3/python21.py", line 17
    get_data(a =120, 200)
                    ^
SyntaxError: positional argument follows keyword argument

It can be seen from the above example that the parametric pass parameter and keyword pass parameter can be used together. But the premise is that the parametric pass must be before the keyword parameter,

Seven. Default parameter

If a parameter is not specified when calling a function, the Python  interpreter will throw an exception. In order to solve this problem, Python allows setting default values ​​for parameters, that is, when defining a function, directly assign a default value to the formal parameters. In this case, even if a parameter with a default value is not passed when the function is called, the parameter can directly use the default value set when the function is defined.

def get_data(a, b = 200):
    d = a + 100 * b
    print(d)

#  关键字传参
get_data(a= 100 )

20100

The above code function needs to receive two parameters. However, we only passed one parameter when calling. The code runs normally and the correct results are obtained because we set the default parameters for b. When calculating, if b is not passed, then use the default 200 to participate in the calculation. What happens if a variable set with default parameters is passed a value when the function is called?

def get_data(a, b=200):
    d = a + 100 * b
    print(d)

#  关键字传参
get_data(100, 300)

30100

We found that although we set the default parameters for b at this time. However, the value of b was also passed at the time of the call. At this time b is no longer using the default value but the actual parameter value.

def get_data(b=200, a):
    d = a + 100 * b
    print(d)

get_data(100)

  File "/Users/apple/Documents/重要文件/python3/python21.py", line 12
    def get_data(b=200, a):
                ^
SyntaxError: non-default argument follows default argument

--------------------------------


def get_data(b=200, a):
    d = a + 100 * b
    print(d)

get_data(a = 100)

  File "/Users/apple/Documents/重要文件/python3/python21.py", line 12
    def get_data(b=200, a):
                ^
SyntaxError: non-default argument follows default argument

It should be noted through the above code: First, the mandatory parameters are in the front, and the default parameters are in the back, otherwise the Python interpreter will report an error

Published 28 original articles · Like 117 · Visits 30,000+

Guess you like

Origin blog.csdn.net/qq_25502269/article/details/105667744