Detailed explanation of the difference between *args and **kwargs in Python programming
- 2021-12-09 09:17:38
- OfStack
I believe that the friends who learn Python must have such an embarrassing situation that giving a function will not be used.
The reason is: I don't know what the types in the parameter list mean, for example, beginners will wonder: how to use *args and **kwargs.
When you know this, I guess you will be able to use many functions!
Usage of # * args: When the number of parameters passed in is unknown and the parameter name is not needed.
def func_arg(farg, *args):
print("formal arg:", farg)
for arg in args:
print("another arg:", arg)
func_arg(1,"youzan",'dba','4 Block 5 The girl ')
print("-----------------------")
# The output is as follows:
#formal arg: 1
# another arg: youzan
# another arg: dba
# another arg: A girl for 4.50 yuan
# -----------------------
Usage of # **kwargs: When the number of parameters passed in is unknown, but the name of the parameter needs to be known (immediately think of dictionary, that is, key-value pair)
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 Block 5 The girl is = ' There is a long way to go ')
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 with 4.50 is: There is a long way to go
Use it to convert parameters to dictionaries
def kw_dict(**kwargs):
return kwargs
print(kw_dict(a=1,b=2,c=3))
The output is as follows:
# --------------------
# {'a': 1, 'b': 2, 'c': 3}
The above is the detailed explanation of the difference between * args and **kwargs in Python programming. For more information about * args and **kwargs in Python, please pay attention to other related articles on this site!