Small series very like in the blog to write on some small issues of opinion, in fact, many small problems do not solve the words, and finally to learn Python is very difficult, so I learn python this thing, or more attention to detail, has been listening to the teacher lectures, are using *args and **kwargs these two parameters, That many people also use, follow the teacher Tiger, but really know the meaning of it?
When the parameters of a function are indeterminate, you can use *args and **kwargs,*args without a key value, **kwargs has a key value.
Let 's say this: This is a python function variable parameter args and Kwargs
*args represents any number of nameless parameters, which is a tuple
**kwargs represents the keyword argument, which is a dict
If that's not the theory, it sounds a little crazy, so I'll give you an example
First of all, give *args:
def highschool_class (Number,*args): print ("The Highschool_class has %s"%number) #高中一个班级的人数 Print ( *args) return (args) Highschool_class (59,30,29)
The result is:
The Highschool_class has a 29Process finished with exit code 0
The following examples **kwargs:
def highschool_class (Number,*args,**kwargs): print ("The Highschool_class has %s"%number) #高中一个班级的人数 print (*args) print (Kwargs) return (Args,kwargs) highschool_class (59,30,29,male = ' $ ', female = ' 29 ')
The result is:
The Highschool_class has 29{' male ': ' A ', ' female ': '}process finished with exit code 0
In contrast, we do not lose values for *args and **kwargs, which is clearer:
def highschool_class (Number,*args,**kwargs): print ("The Highschool_class has %s"%number) #高中一个班级的人数 print (*args) print (Kwargs) return (Args,kwargs) Highschool_class (59)
Results:
The Highschool_class have }process {finished with exit code 0
In fact, with debugging can be seen more clearly:
The use of these two mutable parameters is very clear, the following summary, *args represents any number of nameless parameters, it is a tuple;**kwargs represents the keyword parameter, it is a dict. And when using *args and **kwargs at the same time, *args must be in front of **kwargs.
Of course, these two parameters can also be used separately, and here is a classic example of creating a dictionary:
def class_dict (**kwargs): print (Kwargs) return kwargsclass_dict (a=1,b=2,c=3,d=4)
Results:
{' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4} Process finished with exit code 0
Usage of *args and **kwargs in Python