How to use Python's *args and **kwargs

高洛峰
Release: 2017-03-19 15:05:18
Original
1070 people have browsed it

*args represents any multiple unnamed parameters, which is a tuple; **kwargs represents keyword parameters, which is a dict.

def fun(*args, **kwargs):
    print 'args = ', args
    print 'kwargs = ', kwargs
    print '###'
if name == 'main':
    foo(1,2,3,4)
    foo(a=1,b=2,c=3)
    foo(1,2,3,4, a=1,b=2,c=3)
    foo('a', 1, None, a=1, b='2', c=3)
Copy after login

The output results are as follows:

args =  (1, 2, 3, 4) 
kwargs =  {} 
###
args =  () 
kwargs =  {'a': 1, 'c': 3, 'b': 2} 
###
args =  (1, 2, 3, 4) 
kwargs =  {'a': 1, 'c': 3, 'b': 2} 
###
args =  ('a', 1, None) 
kwargs =  {'a': 1, 'c': 3, 'b': '2'} 
###
Copy after login


As you can see, these two are variable parameters in python .

Note: When using *args and **kwargs at the same time, the *args parameter must be listed before **kwargs, like foo(a=1, b='2', c=3, a', 1, None, ) will prompt Syntax error"SyntaxError: non-keyword arg after keyword arg" if called in this way.

def fun2(param1, *args, **kwargs):
    print 'param1 = ', param1
    print 'args = ', args
    print 'kwargs = ', kwargs
    print '###'
fun2(1, 2, 3, 4, a=1,b=2,c=3)
Copy after login

Output result:

param1 =  1
args =  (2,3,4)
kwargs =  {'a': 1, 'c': 3, 'b': 2} 
###
Copy after login

1 is assigned to param1, the remaining 2, 3, and 4 are assigned to *args, and the others are assigned to **kwargs


There is also a very beautiful usage, which is to create a dictionary:

def kw_dict(**kwargs):
    return kwargs
print kw_dict(a=1,b=2,c=3)
Copy after login

Result:

{'a':1, 'b':2, 'c':3}
Copy after login

In fact, there is a dict class in python. Use dict(a=1,b=2,c=3) to create a dictionary.


The above is the detailed content of How to use Python's *args and **kwargs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!