DAY 8. *args和**kwargs
*args
: Multi-value tuples, **kwargs
multi-valued dictionaries, when they are python function parameter passing two special parameters, args and kwargs not mandatory, but the habit of using these two, if declared in the function parameter list *args
, then allowed to pass any number of parameters of the extra parameters will be assigned the variable args tuple of the form, and **kwargs
allows you to use the variable name is not defined, will pass parameters explicitly packaged into dictionaries
def output(*args, **kwargs):
print(args)
print(kwargs)
output('zhangsan', 'lisi', 5, 6,a=1,b=2,c=3)
# ('zhangsan', 'lisi', 5, 6)
# {'a': 1, 'b': 2, 'c': 3}
From left to right will control the function assignment if there are other parameters, passing parameters, so be sure to put *args
and **kwargs
on the last function parameter list, otherwise it will throw a TypeError exception, and *args
must be placed in **kwargs
front of the correct order of the arguments should be
def fun(arg, *args, **kwargs):
pass
It can also be used when calling the function *
and**
def put(a, b, c):
print(f'a={a},b={b},c={c}')
put(*mylist) # a=aardvark,b=baboon,c=cat
s = {'a': 1, 'b': 2, 'c': 3}
put(**s) # a=1,b=2,c=3
Has been able to achieve this function, the principle is the sequence unpacked, the following brief sequence unpacking
>>> s = "ABCDE"
>>> a,b,c,d,e = s
>>> a,c
('A', 'C')
>>> t = (1,2,3,4,5)
>>> a1,b1,c1,d1,e1 = t
>>> a1,c1
(1, 3)
The above sequence is used to unpack, left and right ends of the number of elements must be equal, otherwise it will throw ValueError exception
>>> a2,b2 = s
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a2,b2 = s
ValueError: too many values to unpack (expected 2)
But we can not all sequences correspond to, if there are a lot of bit sequence or uncertain how many of the use of sequence unpacking it is very convenient, this time we can use *
and the
>>> a3,*a4 = s
>>> a3,a4
('A', ['B', 'C', 'D', 'E'])
>>> while s:
f,*s = s
print(f,s)
A ['B', 'C', 'D', 'E']
B ['C', 'D', 'E']
C ['D', 'E']
D ['E']
E []
Reference article:
Detailed Python unpacking sequence (4)