What is the difference between * args and * * kwargs in Python
This article mainly introduces the difference between * args and * * kwargs in Python, which has a certain reference value. Interested friends can refer to it. I hope you can learn a lot after reading this article.
I believe that friends who learn from Python must have such an awkward situation, giving a function can not be used.
The reason is: do not know the meaning of the type in the parameter list, for example, beginners will ask: * args and * kwargs exactly how to use.
When you know this, I guess you can use a lot of functions!
# * usage of args: when the number of parameters passed is unknown and you do not need to know the parameter name.
Def func_arg (farg, * args): print ("formal arg:", farg) for arg in args: print ("another arg:", arg) func_arg (1, "youzan", 'dba',' $4.50') print ("- -")
# the output is as follows:
# formal arg: 1
# another arg: youzan
# another arg: dba
# another arg: a girl of $4.50
#
# * * usage of kwargs: when the number of parameters passed in is unknown, but you need to know the name of the parameter (you immediately think of a dictionary, that is, key-value pairs)
Def func_kwargs (farg, * * kwargs): print ("formal arg:", farg) for key in kwargs: print ("keyword arg:% s:% s"% (key, kwargs [key])) func_kwargs (1, id=1, name='youzan', city='hangzhou',age ='20', $4.50) print ('-')
# the output is as follows:
# formal arg: 1
# keyword arg: id: 1
# keyword arg: name: youzan
# keyword arg: city: hangzhou
# keyword arg: age: 20
# keyword arg: the girl who costs $4.50 will have a long time to come.
Use it to convert parameters to dictionaries
Def kw_dict (* * kwargs): return kwargsprint (kw_dict (axi1 ~ 2 ~ 3))
The output is as follows:
#-
# {'asides: 1,' breadth: 2, 'cations: 3}
Thank you for reading this article carefully. I hope the article "what is the difference between * args and * * kwargs in Python" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!