1. Default value parameters
Sometimes, in our custom functions, if there are no parameters set when calling, we need to give a default value, which is needed at this time. Default value parameter.
# -*- 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 性别:男
You can see that when you set the default parameter, when calling the function, if you do not pass the parameter, the default value will be used. But one thing to note here is: only those parameters at the end of the formal parameter list can have default parameter values. That is to say, when declaring function parameters, you cannot first declare parameters with default values and then declare parameters without default values. formal parameters. This is because the values assigned to formal parameters are assigned positionally. For example, def func(a, b=1) is valid, but def func(a=1, b) is invalid.
Is this the end of the default value parameters? Not yet, think about it carefully, if the parameter is a modifiable container such as an lsit (list) or dict (dictionary), then what should we use as the default value? We can use None as the default value. Just like the following example:
# 如果 b 是一个 list ,可以使用 None 作为默认值 def print_info( a , b = None ): if b is None : b=[] return;
Look at the example carefully. Do you have any such questions? Can't we just use b=[] directly in the parameters? That is, it is written like this:
def print_info( a , b = [] ): return;
, right? No errors were found after running it. Can I write it like this? One thing that needs special attention here: the value of the default parameter is an immutable object, such as None, True, False, number or string. If you operate as above, you will encounter problems 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.
Examples are as follows:
# -*- coding: UTF-8 -*- def print_info( a , b = [] ): print(b) return b ; result = print_info(1) result.append('error') print_info(2)
Output results:
[] ['error']
Observe carefully, you will find that the second output value is not what you want at all, so avoid this. operate.
One more thing, 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;
The object here is the base class of all classes in python. You can create instances of the object class, but these instances are of no real use because it doesn't have any useful methods, nor does it have any instance data (because it doesn't have any instance dictionary, you can't even set any property values). The only thing you can do is test for identity. This feature can also be used to determine whether there is a value input.
2. Keyword parameters
In Python, you can pass parameters to a function through parameter names without caring about the order in which the parameter list is defined. This is called It is a keyword parameter. There are two advantages to using key parameters:
First, using functions becomes simpler because we don’t have to worry about the order of parameters.
2. Assuming that other parameters have default values, we can only assign values to those parameters we want
# -*- 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 性别:女
3. Indefinite length parameters
Sometimes when we design a function interface, we may need variable-length parameters. In other words, we cannot determine the number of parameters passed in in advance. Python provides a tuple method to accept parameters that are not directly defined. This method adds an asterisk * in front of the parameter. If no parameters are specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to the function.
For example:
# -*- 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 output result:
昵称:两点水 年龄:18 性别:女 爱好:('打篮球', '打羽毛球', '跑步')
You can know from the output result that *hobby is a variable parameter, and hobby is actually a tuple (original ancestor)
Variable length parameters also support key parameters. Undefined key parameters will be placed in 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 = ('打篮球','打羽毛球','跑步'))
Output result:
昵称:两点水 年龄:18 性别:女 爱好:{'hobby': ('打篮球', '打羽毛球', '跑步')}
By comparing the above example with this example, we can know that *hobby is a variable parameter, and hobby is actually a tuple (original ancestor), **hobby is a keyword parameter, and hobby is a dict (dictionary)
4. Only accept keyword parameters
Keyword parameters are easy to use and are not prone to parameter errors. So sometimes, the functions we define want certain parameters to be passed using keyword parameters. What should we do at this time?
This effect can be achieved by placing the mandatory keyword parameters after a * parameter or a single *, 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='男')
You can see from the example that if age and sex keywords are not applicable Parameters will report errors.
In many cases, using mandatory keyword parameters will make the meaning clearer than using positional parameters, and the program will be more readable. Using mandatory keyword parameters is also better than using **kw parameters and mandatory keyword parameters are also useful in some more advanced situations.
Next Section