Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use python variable length parameters * args and * * kwargs

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use python variable length parameters * args and * * kwargs". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to use the python variable length parameters * args and * kwargs"!

In functions written in python language modules, you can often see these two parameters in the function's parameter table column, such as:

Def some_function (* args, * * kwargs): to do list return 0

First of all, explain the function of an asterisk. The function of an asterisk * is to unpack the elements in tuple or list and pass them separately as multiple parameters; the function of two asterisks * * is to pass in data of type dict as parameters.

Kwargs is the abbreviation of keyword argument, and args is argument. We know that there are two kinds of parameters in Python, one is called position parameter (positional argument), the other is called keyword parameter (keyword argument), the keyword parameter only needs to use the method of keyword = somekey to pass parameters, and the position parameter can only be determined by the position of the parameter. This also determines that the location parameter must be in front, otherwise the change in the number of keyword parameters (for example, some kwargs have default values and therefore do not pass parameters or pass parameters later), will make the location impossible to determine. Therefore, it is also common that * args is in front of * kwargs.

Topic description:

1. How to understand the variable length parameter?

2. What do * args and * * kwargs mean? Why use them?

The main points of the answer are as follows:

1. Function parameters can be divided into the following categories: required parameters, default parameters, variable parameters, named keyword parameters and keyword parameters.

2. When we define and call a function, if we include all parameter types, we must follow the order of required parameters, default parameters, variable parameters, named keyword parameters and keyword parameters. However, in actual development, it is not recommended to include too many parameter types, which will affect the readability of the code.

3. The required parameters are very simple, that is, the parameters that must be accepted in the function.

4, the default parameter, that is, assign a default value to the parameter. When we pass it, we can omit the operation of passing the value of the parameter. Such as:

Def print_test (title, msg= "world"): print (title, msg) print_test ("hello") # hello worldprint_test ("hello", "demon") # hello demonprint_test ("hello", msg= "demon") # hello demon# error call example # print_test (msg= "demon", "hello") # this is wrong

5. Variable parameters are accepted by * args when defining the function, in which * is specified. Args can be replaced by another name, but it is customary to use args to express it. After passing in the function, the variable parameter is encapsulated into a tuple for use. So inside the function, we can manipulate parameters by manipulating tuple. The example is as follows:

Def print_numbers (* args): print (type (args)) # tuple for n in args: print (type (n)) # intprint_numbers (1,2,3,4)

6. If you have already got a list or tuple outside the function and want to call a variable parameter, you can also call it in the form of * + variable name (this usage is somewhat similar to the pointer in C language). The example is as follows:

Def print_numbers (* args): print (type (args)) # tuple for n in args: print (type (n)) # intl = [1,2,3,4] print_numbers (* l) # * l, which is equivalent to print_numbers (1,2,3,4) print_numbers (l) # passing l as a whole, so that the function accepts only one parameter, and the parameter type is list.

7. Keyword parameters are identified by kwargs, which is specified, while kwargs is replaceable, which converts indefinite length parameters into dict input functions. It is used to extend the function of the function. For example, if we want to achieve user registration, there are required and non-required entries, which can be accepted with keyword parameters. Examples are as follows:

Def register (name, email, * * kwargs): print ('name:%s, age:%s, others:%s', (name, email, kwargs)) register ("demon", "1@1.com") # name:%s, age:%s, others:%s (' demon','1) shanghai, {}) register ("demon", "1@1.com", addr= "shanghai") # name:%s, age:%s Others:%s ('demon',' 1. Compositions, {'addr':' shanghai'})

8. If you have already obtained a dict outside the function, you can simply pass it with the variable name of * * + if you want to call the function. And the dict example is as follows:

Def register (name, email, * * kwargs): print ('name:%s, age:%s, others:%s', (name, email, kwargs)) d = {"addr": "shanghai"} register ("demon", "1@1.com", * * d) d = {"name": "yrr", "email": "1@1.com", "addr": "shanghai"} register (* * d) d = {"email": "yrr" "name": "1@1.com", "addr": "shanghai"} register (* d)

9. The named keyword parameter is used to limit the attributes that can be passed in to the calling function. The restriction here is a false restriction, because it can still be passed in, but no processing is done to the parameters outside the restriction in the function body. The named keyword parameters are separated by a * sign, and the parameters that follow the * are treated as named keyword parameters. Such as:

Def person (name, age, *, city, job): print (name, age, city, job)

10. If a variable parameter is already defined in the function, there is no need to add * to the following named keyword parameters, such as:

Def person (name, age, * args, city, job): print (name, age, args, city, job)

Keyword parameters and named keyword parameters must be called in the form of key=value, which we call name parameters, but do not need to specify the parameter name of the parameter, also known as position parameters. Both required and variable parameters can be matched by position parameters. Such as:

Def register (name, email, * * kwargs): print ('name:%s, age:%s, others:%s', (name, email, kwargs)) # error call: register ("123,123", "123") # it will take the third parameter" 123" >

12. The last one is special and a conclusion: any function can be called in the form of func_name (* args, * * kw), where args is a list or tuple that has been obtained, and kw is a dictionary that has been obtained. The list input will assign values to the required parameters in order, the excess parameters will be passed as variable parameters, and the dictionary input will match all parameters according to key. Such as:

Def test1 (a, b, cym0, * args, * * kwargs): print ('a =', a,'b =', b,'c =', c, 'args=', args,' kw =', kwargs) def test2 (a, b, cym0, * args, d, * * kwargs): print ('a =', a,'b =', b,'c =', c, d =', d, 'args=', args,' kw =' Kwargs) # define a tuple and dictionary as parameters passing args= (1, 2, 3, 4) kw = {'dudes: 99,' xwords:'#'} test1 (* args, * * kw) # a = 1b = 2c = 3 args= (4,) kw = {'dwells: 99,' xwords:'#'} test2 (* args, * * kw) a = 1b = 2c = 3d = 99 args= (4) ) kw = {'xcow:' #'} so far I believe you have a deeper understanding of "how to use python variable length parameters * args and * kwargs". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report