TOC
What do *args
and **kwargs
mean in python function?
*args
means we can pass an arbitrary number of arguments to the function;
Similarly, **kwargs
allow we pass many key=value
argument to the function;
*args
*args
iterable:
def my_sum(*args):
result = 0
# Iterating over the Python args tuple
for x in args:
result += x
return result
print(my_sum(1, 2, 3))
# output: 6
The *
is a unpacking operator;
def print_three_things(a, b, c):
print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
mylist = ['aardvark', 'baboon', 'cat']
print_three_things(*mylist)
# output: a = aardvark, b = baboon, c = cat
**kwargs
example
**kwargs
iterable:
mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals()))
REFERENCE:
1.use-of-args-and-kwargs 2.python-kwargs-and-args
「点个赞」
点个赞
使用微信扫描二维码完成支付
