picture

Third, the parameters of the function

1. The parameter type of the function



Setting and passing parameters is the focus of functions, and Python's function support for parameters is very flexible.
The main parameter types are: default parameters, keyword parameters (positional parameters), and variable-length parameters.

Below we will understand these parameters one by one.

2. Default parameters



Sometimes, in our custom function, if there is no parameter set when calling, we need to give a default value. In this case, we need to use the default value parameter.
Default parameters, as long as you assign values ​​to the parameters in the constructor parameters

E.g:

# -*- coding: UTF-8 -*-
def print_user_info( name , age , sex = '男' ): # 打印用户信息 print('昵称:{}'.format(name) , end = ' ') print('年龄:{}'.format(age) , end = ' ') print('性别:{}'.format(sex)) return;
# 调用 print_user_info 函数
print_user_info( '两点水' , 18 , '女')print_user_info( '三点水' , 25 )

Output result:

昵称:两点水 年龄:18 性别:女昵称:三点水 年龄:25 性别:男

As you can see from the output, when you set a default parameter, when calling the function, if the parameter is not passed, the default value will be used.
But one thing to note here is that only those parameters at the end of the formal parameter list can have default parameter values, which means that you cannot declare a function parameter with a default value first and then declare a parameter without a default value. formal parameters.
This is because the value assigned to the formal parameter is assigned positionally. For example, def func(a, b=1) is valid, but def func(a=1, b) is invalid.
Is this the end of default value parameters?
Not yet, think about it, if the parameter is a modifiable container such as an lsit (list) or dict (dictionary), then what do we use as the default value?
We can use None as the default value. Like this example:
# 如果 b 是一个 list ,可以使用 None 作为默认值def print_info( a , b = None ):    if b is None :        b=[]    return;

Look carefully at the example, will there be such a question? Can we just b=[]not ?

That is, it is written like this:

def print_info( a , b = [] ):    return;

right?

I didn't find any errors after running it, can I write it like this?

A special note here: the value of the default parameter is an immutable object, such as None, True, False, a number or a string , if you do it like the above, you will encounter when the default value is modified elsewhere to all kinds of trouble.

These changes will affect the default value the next time this function is called.

An example is as follows:

# -*- coding: UTF-8 -*-
def print_info( a , b = [] ): print(b) return b ;
result = print_info(1)
result.append('error')
print_info(2)

The result of the output:

[]['error']

If you look carefully, you will find that the value of the second output is not what you want at all, so don't do this.
Another point, sometimes I just don't want the default value, I just want to judge whether the default parameter has a value passed in, what should I do?

We can do this:

_no_value =object()
def print_info( a , b = _no_value ): if b is _no_value : print('b 没有赋值') return;

Here objectis the base class for all classes in python. You can create instances of the objectclass , but these instances are of little practical use, since it doesn't have any useful methods, nor any instance data (because it doesn't have any instance dictionary, and you can't even set any property values). The only thing you can do is test for identity. This feature is also used to determine whether there is a value input.

3. Keyword arguments (positional arguments)


Under normal circumstances, when we need to pass parameters to a function, we must come in order. If it does not correspond to the order, the wrong value will be passed.
In Python, however, you can pass parameters to a function by parameter name, regardless of the order in which the parameter list is defined. This is called keyword arguments.
Using key parameters has two advantages:
  • Since we don't have to worry about the order of the arguments, using functions is much simpler.

  • Assuming other parameters have default values, we can assign values ​​to only those parameters we want

Specifically look at the example:

# -*- coding: UTF-8 -*-
def print_user_info( name , age , sex = '男' ): # 打印用户信息 print('昵称:{}'.format(name) , end = ' ') print('年龄:{}'.format(age) , end = ' ') print('性别:{}'.format(sex)) return;
# 调用 print_user_info 函数
print_user_info( name = '两点水' ,age = 18 , sex = '女')print_user_info( name = '两点水' ,sex = '女', age = 18 )

Output value:

昵称:两点水 年龄:18 性别:女昵称:两点水 年龄:18 性别:女

4. Variable length parameters


Maybe sometimes, when we design a function, we sometimes cannot determine the number of parameters passed in.
Then we can use variable length parameters.
Python provides a tuple way to accept arguments that are not directly defined. This way add an asterisk in front of the parameter *.
If no arguments are specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to the function.

E.g:

# -*- coding: UTF-8 -*-
def print_user_info( name , age , sex = '男' , * hobby): # 打印用户信息 print('昵称:{}'.format(name) , end = ' ') print('年龄:{}'.format(age) , end = ' ') print('性别:{}'.format(sex) ,end = ' ' ) print('爱好:{}'.format(hobby)) return;
# 调用 print_user_info 函数print_user_info( '两点水' ,18 , '女''打篮球','打羽毛球','跑步')

The result of the output:

昵称:两点水 年龄:18 性别:女 爱好:{'hobby': ('打篮球', '打羽毛球', '跑步')}

It can be known from the output result that it *hobbyis a variable parameter, and hobby is actually a tuple (tuple)
Variable-length parameters also support keyword parameters (positional parameters), and key parameters that are not defined will be put into a dictionary.

This method is to add in front of the parameter **, and change the above example as follows:

# -*- coding: UTF-8 -*-
def print_user_info( name , age , sex = '男' , ** hobby ): # 打印用户信息 print('昵称:{}'.format(name) , end = ' ') print('年龄:{}'.format(age) , end = ' ') print('性别:{}'.format(sex) ,end = ' ' ) print('爱好:{}'.format(hobby)) return;
# 调用 print_user_info 函数print_user_info( name = '两点水' , age = 18 , sex = '女', hobby = ('打篮球','打羽毛球','跑步'))

The result of the output:

昵称:两点水 年龄:18 性别:女 爱好:{'hobby': ('打篮球', '打羽毛球', '跑步')}

By comparing the above example and this example, we can know that it *hobbyis a variable parameter, and hobby is actually a tuple (tuple), **hobbya keyword parameter, and hobby is a dict (dictionary)

5. Only accept keyword arguments


Keyword parameters are easy to use, and it is not easy to make parameter errors. So sometimes, the functions we define want to force some parameters to be passed using keyword parameters. What should we do at this time?

This effect can be achieved by placing mandatory keyword arguments after a *parameter or a single one, for example:*

# -*- coding: UTF-8 -*-
def print_user_info( name , *, age , sex = '男' ): # 打印用户信息 print('昵称:{}'.format(name) , end = ' ') print('年龄:{}'.format(age) , end = ' ') print('性别:{}'.format(sex)) return;
# 调用 print_user_info 函数print_user_info( name = '两点水' ,age = 18 , sex = '女' )
# 这种写法会报错,因为 age ,sex 这两个参数强制使用关键字参数#print_user_info( '两点水' , 18 , '女' )print_user_info('两点水',age='22',sex='男')

As you can see from the example, if you agedo sexnot use keyword arguments, an error will be reported.

In many cases, using mandatory keyword arguments is more explicit and more readable than using positional arguments. Using mandatory keyword arguments is also better than using **kwparameters and mandatory keyword arguments can also be useful in some more advanced situations.

Featured Article Recommendations





Follow me and catch the latest and most trendy black technology together