In-depth explanation of the use of parameters in Python functions and the traps of default parameters, python traps
The default parameters can be set for functions in C ++, but cannot be set in Java. They can only be implemented through reload. in python, the default parameters can also be set. The biggest benefit is to reduce the difficulty of functions, there is only one function definition, and python is a dynamic language. There cannot be a function with multiple names in the same namespace. If so, the subsequent function will overwrite the previous function.
def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s
Look at the results:
>>> power(5)25>>> power(5,3)125
Note: The required parameter is in the front, and the default parameter is in the back; otherwise, an error is reported in the Python interpreter.
Suggestion: * When a function has multiple parameters, put the parameters with large changes before them and those with small changes after them. A parameter with a small change can be used as the default parameter.
The default parameters are also pitfall. Let's look at the following code. First define a list, add an end, and then return:
def add_end(L=[]): L.append('END') return L
Check the call result:
>>> add_end([1, 2, 3])[1, 2, 3, 'END']>>> add_end(['x', 'y', 'z'])['x', 'y', 'z', 'END']>>> add_end()['END']>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']
Here, we need to explain that when a Python function is defined, the value of the default parameter L is calculated, that is, []. L points to []. So if the content in L changes, the content referenced in the next call will no longer be. So remember that the default parameter must point to an immutable object !.
Variable parameters
First, the input parameter is a list or tuple.
def calc(numbers): sum = 0 for n in numbers: sum = sum + n * n return sum
Call method:
>>> calc([1, 2, 3])14>>> calc((1, 3, 5, 7))84
In the second method, multiple parameters are directly input, and a tuple is automatically received in the function.
def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum
Call method:
>>> calc(1, 2)5>>> calc()0
If you want to upload data in a list or tuple, you can do this:
>>> nums = [1, 2, 3]>>> calc(*nums)14
Keyword Parameter
Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict in the function.
def person(name, age, **kw): print 'name:', name, 'age:', age, 'other:', kw
Call example:
>>> person('Michael', 30)name: Michael age: 30 other: {}>>> person('Bob', 35, city='Beijing')name: Bob age: 35 other: {'city': 'Beijing'}>>> person('Adam', 45, gender='M', job='Engineer')name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
Parameter combination
Define functions in Python. You can use required parameters, default parameters, variable parameters, and keyword parameters. These four parameters can be used together or only use some of them, the order of parameter definitions must be: mandatory parameter, default parameter, variable parameter, and keyword parameter.
Recursive functions
Basically, there is nothing to talk about. Like Java/C ++, it is a kind of calling itself. Here we will focus on tail recursion optimization. In fact, tail recursion has the same effect as loop. Obviously, it can prevent stack overflow of recursive calls.
Definition: Calls itself when the function returns, and the return statement cannot contain expressions. The compiler or interpreter can optimize it. No matter how many calls are made, it only occupies one stack frame and will not overflow.
Here is a simple example:
def fact(n): if n==1: return 1 return n * fact(n - 1)
If the input n is large, it may overflow. This is because return n * fact (n-1) introduces a multiplication expression, so it is not tail recursion. Modify the Code:
def fact(n): return fact_iter(n, 1)def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product)
Default parameter traps
The Function Definition of Python provides the default parameter option, which makes the definition and usage of the function more flexible, but also brings some pitfalls, such as the previous example:
Function Definition:
def add_end(L=[]): L.append('END') return L
Result of calling the function:
>>> add_end([1, 2, 3])[1, 2, 3, 'END']>>> add_end(['x', 'y', 'z'])['x', 'y', 'z', 'END']>>> add_end()['END']>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']
Obviously, this is not consistent with the original definition of the function. It is explained in one sentence:
Default values are computed once, then re-used.
To study this problem in depth, let's look at another example:
# Coding = utf-8def a (): print "a executed" return [] def B (x = a (): print "id (x):", id (x) x. append (5) print "x:", xfor I in range (2): print "without parameters, use the default parameter" B () print B. _ defaults _ print "id (B. _ defaults _ [0]): ", id (B. _ defaults _ [0]) for I in range (2): print "with parameter call, input a list" B (list () print B. _ defaults _ print "id (B. _ defaults _ [0]): ", id (B. _ defaults _ [0])
NOTE: All default values are stored in the _ ults _ attribute of the function object. This is a list and each element is a default parameter value.
Let's take a look at the output:
A executed is called without parameters. Use the default parameter id (x): 14003885420.552x: [5] ([5],) id (B. _ defaults _ [0]): 140038854650552 No parameter call. Use the default parameter id (x): 14003885420.552x: [5, 5] ([5, 5],) id (B. _ defaults _ [0]): 140038854650552 call with parameters. Input a listid (x): 140038854732400x: [5] ([5, 5],) id (B. _ defaults _ [0]): 140038854650552 call with parameters. Input a listid (x): 140038854732472x: [5] ([5, 5],) id (B. _ defaults _ [0]): 140038854650552
A Brief Analysis of the output results:
1st rows
When defining function B (), that is, executing the def statement and code line 7th def B (x = a ():, the default parameter is used, therefore, the default parameter x is calculated during definition, and a () is called at this time, so a executed is printed.
2nd ~ 6 rows
During the first execution of the loop, the first line of code calls B () without passing the parameter. Use the default parameter. At this time, x = [], so after one call
print b.__defaults__
The output result is
Copy codeThe Code is as follows: ([5],)
7th ~ 11 rows
In the second loop, the default parameter is used to call B () in line 2 of the code without passing the parameter.
Note: The default parameter is calculated only once, that is, the memory area is fixed, but the address points to a list and the content can be changed. In this case, the last call of x: [5], so
print b.__defaults__
The output result is
([5, 5],)
12th ~ 16 rows
The second loop statement, the first loop, passes in an empty list in line 20th of code, so no default parameter is used. At this time, x = [], so
print b.__defaults__
The output result is
Copy codeThe Code is as follows: ([5],)
18th ~ 21 rows
The second loop statement, the second loop, passes in an empty list in line 20th of the code, so the default parameter is not used. At this time, it is still x = [], so
print b.__defaults__
The output result is still
Copy codeThe Code is as follows: ([5],)
A function is also an object, so it is executed when it is defined. The default parameter is the property of the function, and its value may change as the function is called. Is this true for other objects?
Keep in mind: default parameters must point to unchanged objects! The code is changed as follows:
# Coding = utf-8def a (): print "a executed" return Nonedef B (x = a (): print "id (x):", id (x) if x is None: x = [] x. append (5) print "x:", xfor I in range (2): print "without parameters, use the default parameter" B () print B. _ defaults _ print "id (B. _ defaults _ [0]): ", id (B. _ defaults _ [0]) for I in range (2): print "with parameter call, input a list" B (list () print B. _ defaults _ print "id (B. _ defaults _ [0]): ", id (B. _ defaults _ [0])
At this time, let's see what the output result is:
A executed is called without parameters. Use the default parameter id (x): 9568656x: [5] (None,) id (B. _ defaults _ [0]): 9568656 No parameter call. Use the default parameter id (x): 9568656x: [5] (None,) id (B. _ defaults _ [0]): 9568656 is called with parameters. Input a listid (x): 140725126699632x: [5] (None,) id (B. _ defaults _ [0]): 9568656 call with parameters. Input a listid (x): 140725126699704x: [5] (None,) id (B. _ defaults _ [0]): 9568656
Articles you may be interested in:
- Use * args and ** kwargs in Python functions to pass variable length parameters
- Python Variable Parameter Function usage example
- Introduction to parameter passing and variable length parameters of functions in Python
- Description of type constructor parameters in Python
- Analysis of parameter definitions and Variable Parameter usage of functions in Python
- Examples of Variable Parameter definitions and parameter passing methods of Python Functions
- Measure the test taker's understanding about function parameters in Python.
- In-depth discussion of the causes of the default values of Python Functions
- Python uses the decorator to check the data type of function parameters
- Detailed description of Python custom function creation, calling, and function parameters