When defining a function, we determine the name and position of the parameter, and the interface definition of the function is complete. For the caller of the function, it's enough to know how to pass the correct arguments, and what values the function will return, and the complex logic inside the function is encapsulated, and the caller doesn't need to know.
Python's function definition is very simple, but the flexibility is very large. In addition to the required parameters that are normally defined, you can use default parameters, variable parameters, and keyword parameters so that the interface defined by the function can handle complex parameters as well as simplify the caller's code.
Default Parameters
We still use concrete examples to illustrate how to define the default parameters for a function. First write a function to compute x2:
def power (x): Return
x * x
When we call the power function, we must pass in the only one parameter x:
>>> Power (5)
-
>>> Power (225)
Now, what if we're going to compute x3? You can define a power3 function, but if you want to compute x4, x5 ... What to do? We cannot define infinitely many functions.
You may have thought that power (x) could be changed to power (x, N) to compute xn and dry:
def power (x, N):
s = 1 while
n > 0:
n = n-1
s = S * x return
S
For this modified power function, you can compute any n-second party:
>>> Power (5, 2)
>>> Power (5, 3)
125
However, the old calling code failed because we added a parameter that caused the old code to not be invoked properly:
>>> Power (5)
Traceback (most recent called last):
File "<stdin>", line 1, in <module>
Typeerror:power () takes exactly 2 arguments (1 given)
This time, the default parameters come in handy. Since we often compute x2, we can set the default value of the second parameter N to 2:
def power (x, n=2):
s = 1 while
n > 0:
n = n-1
s = S * x return
S
So, when we call Power (5), it's the equivalent of calling power (5, 2):
>>> Power (5)
>>> Power (5, 2)
25
For other cases of n > 2, you must explicitly pass in N, such as power (5, 3).
As can be seen from the example above, the default parameter simplifies the invocation of the function. When setting default parameters, there are a few things to note:
The first is the required parameter, the default parameter is later, otherwise the Python interpreter will give an error (consider why the default parameter cannot be placed in front of the required parameters);
The second is how to set the default parameters.
When a function has more than one parameter, the parameter that is changed is placed in front, and the small variable is put behind. Parameters that vary little can be used as default parameters.
What are the benefits of using default parameters? The biggest advantage is that it can reduce the difficulty of calling a function.
For example, we write a first-year primary school registration function that requires two parameters to be passed in name and gender:
def enroll (name, gender):
print ' name: ', name
print ' Gender: ', gender
This way, calling the Enroll () function requires only two parameters to be passed in:
>>> enroll (' Sarah ', ' F ')
Name:sarah
gender:f
If you want to continue to pass the age, city and other information how to do? This will greatly increase the complexity of the calling function.
We can set the age and the city as the default parameter:
def enroll (name, Gender, age=6, city= ' Beijing '):
print ' name: ', name
print ' Gender: ', gender
print ' Age: ' , Age
print ' city: ', city
In this way, most students do not need to provide age and city when registering, providing only two parameters that are required:
>>> enroll (' Sarah ', ' F ')
Student:
name:sarah
gender:f
age:6
city:beijing
Only students who are not in conformity with the default parameters need to provide additional information:
Enroll (' Bob ', ' m ', 7)
enroll (' Adam ', ' m ', city= ' Tianjin ')
As you can see, the default parameters reduce the difficulty of the function call, and when more complex calls are required, more arguments are passed to implement. Whether it's a simple call or a complex call, the function only needs to define one.
When multiple default parameters are invoked, the default parameters can be supplied in order, such as calling enroll (' Bob ', ' M ', 7), meaning that, in addition to the Name,gender parameters, the last 1 parameters are applied to the parameter age, and the city parameter is not provided. The default value is still used.
You can also provide partial default parameters in a sequential order. You need to write the parameter names when you do not supply part of the default parameters in order. For example, call Enroll (' Adam ', ' M ', city= ' Tianjin '), meaning that the city parameter uses the values passed in, and the other default parameters continue to use the default values.
The default parameters are useful, but improper use can also fall into the pit. The default parameter has one of the largest pits, as demonstrated below:
First define a function, pass in a list, add an end and return:
def add_end (l=[]):
l.append (' End ') return
L
When you call normally, the result seems to be good:
>>> Add_end ([1, 2, 3])
[1, 2, 3, ' end ']
>>> add_end ([' X ', ' y ', ' z '])
[' x ', ' y ', ' z '], ' end ']
When you use the default parameter invocation, the first result is also true:
However, when you invoke Add_end () again, the result is incorrect:
>>> add_end ()
["End", "End"]
>>> add_end () ["End", "End", "End"
]
Many beginners are puzzled that the default parameter is [], but the function seems to "remember" the list that was last added ' end ' every time.
Explanations for the reasons are as follows:
When the Python function is defined, the value of the default parameter L is computed. That is [], because the default parameter L is also a variable, it points to the object [], each time the function is called, if the contents of L are changed, the contents of the default parameter will be changed at the next call, no longer the [] of the function definition.
So, to define the default parameters, keep in mind that the default argument must point to the invariant object!
To modify the example above, we can implement the invariant object with none:
def add_end (l=none):
if L is None:
l = []
l.append ("End") return
L
Now, no matter how many times you call, there is no problem:
>>> add_end ()
[' End ']
>>> add_end ()
[' End ']
Why do you want to design invariant objects such as STR and none? Because once the invariant object is created, the data inside the object cannot be modified, thus reducing the error caused by the modification of the data. In addition, because the object is invariant, the multitasking environment reads the object without the need for locking, while reading the problem is not. When we write a program, if we can design a invariant object, then try to design unchanged objects.
variable Parameters
In a Python function, you can also define variable parameters. As the name suggests, the variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0.
We take the mathematics titled example, given a set of numbers a,b,c ..., please compute A2 + b2 + C2 + ....
To define this function, we must determine the input parameters. Because the number of parameters is not certain, we first think that we can put a,b,c ... As a list or tuple, so that the function can be defined as follows:
def calc (numbers):
sum = 0 for
n in numbers:
sum = SUM + N * n * return
sum
But when you call, you need to assemble a list or tuple first:
>>> Calc ([1, 2, 3])
>>> Calc ((1, 3, 5, 7))
84
If you take advantage of variable parameters, the way you call a function can be simplified as follows:
>>> Calc (1, 2, 3)
>>> Calc (1, 3, 5, 7)
84
So, we change the parameter of the function to the variable parameter:
Def calc (*numbers):
sum = 0 for
n in numbers:
sum = SUM + N * n * return
sum
When you define a variable parameter and define a list or tuple parameter, you simply add a * number to the parameter. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any of the arguments, including 0 parameters:
>>> Calc (1, 2)
5
>>> calc ()
0
What if you already have a list or tuple to invoke a variable parameter? You can do this:
>>> nums = [1, 2, 3]
>>> Calc (nums[0], nums[1], nums[2])
14
This kind of writing is certainly feasible, the problem is too cumbersome, so python allows you to add a * number in front of the list or tuple, the list or tuple elements into variable parameters to pass in:
>>> nums = [1, 2, 3]
>>> calc (*nums)
14
This kind of writing is quite useful and very common.
keyword Parameters
Variable parameters allow you to pass in 0 or any of the parameters, which are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with a parameter name, which is automatically assembled into a dict within the function. Take a look at the example:
def person (name, age, **kw):
print ' name: ', Name, ' Age: ', age, ' other: ', kw
The function person accepts the keyword parameter kw in addition to the required parameter name and age. When you call the function, you can pass in only the required parameters:
>>> person (' Michael, "
Name:michael age:30 other: {}
You can also pass in any number of keyword parameters:
>>> person (' Bob ', "city= ' Beijing ')
name:bob age:35 Other: {" City ": ' Beijing '}
>>> person ( ' Adam ', gender= ' m ', job= ' Engineer ')
Name:adam age:45 Other: {' Gender ': ' m ', ' job ': ' Engineer '}
What is the use of keyword parameters? It can extend the function of a function. For example, in the person function we are guaranteed to receive both the name and age parameters, but we can also receive it if the caller is willing to provide more arguments. Imagine you are doing a user registration function, in addition to user name and age is required, the other is optional, the use of keyword parameters to define this function can meet the requirements of registration.
Similar to variable parameters, you can also assemble a dict, and then convert the dict to a keyword parameter:
>>> kw = {' City ': ' Beijing ', ' Jobs ': ' Engineer '}
>>> person (' Jack ', city=kw[' city '], job=kw[' Job '])
name:jack age:24: {' City ': ' Beijing ', ' job ': ' Engineer '}
Of course, the complex calls above can be written in simplified notation:
>>> kw = {' City ': ' Beijing ', ' job ': ' Engineer '}
>>> person (' Jack ', **kw)
name:jack age:24 Other: {' City ': ' Beijing ', ' job ': ' Engineer '}
Parameter combinations
To define a function in Python, you can use required parameters, default parameters, variable parameters, and keyword parameters, all 4 of which can be used together, or only some of them, but note that the order in which the parameters are defined must be: required, default, variable, and key parameters.
For example, define a function that contains the 4 parameters mentioned above:
def func (A, B, c=0, *args, **kw):
print ' A = ', A, ' B = ', B, ' C = ', C, ' args = ', args, ' kw = ', kw
When the function is called, the Python interpreter automatically passes the corresponding arguments in the parameter position and the argument name.
>>> func (1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> func (1, 2, c=3)
a = 1 b = 2 c = 3 arg s = () kw = {}
>>> func (1, 2, 3, ' A ', ' B ')
a = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {}
>>> F UNC (1, 2, 3, ' A ', ' B ', x=99)
a = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {' X ': 99}
The most amazing thing is that you can call the function through a tuple and dict:
>>> args = (1, 2, 3, 4)
>>> kw = {' X ':}
>>> func (*args, **kw)
a = 1 b = 2 C = 3 args = (4,) kw = {' X ': 99}
Therefore, for any function, it can be invoked in the form of a similar func (*args, **kw), regardless of how its parameters are defined.
Summary
Python's functions have a very flexible parameter shape that enables both simple calls and very complex parameters.
The default parameter must be used with a mutable object, and if it is a mutable object, the runtime will have a logical error!
Note The syntax for defining variable parameters and keyword parameters:
- *args is a variable parameter, args receives a tuple;
- **KW is the keyword parameter, and kw receives a dict.
And how to pass the syntax of a variable parameter and keyword parameter when calling a function:
- Variable parameters can be directly passed in: Func (1, 2, 3), can be assembled first list or tuple, and then passed through the *args: Func (* (1, 2, 3));
- Keyword parameters can be passed directly into: Func (A=1, b=2), can be assembled dict first, and then passed **kw to: func (**{' a ': 1, ' B ': 2}).
Using *args and **kw is a Python idiom, and of course you can use other parameter names, but it's best to use idiomatic usage.