Python's variable parameter *args,**kwargs and differences

Source: Internet
Author: User
Tags in python


You can often see *args and **kwargs in Python's function arguments, which is the magic parameter of Python, a variable parameter that supports passing in multiple parameters, and look at the difference between them.


*args represents any number of unnamed parameters, it is a tuple;**kwargs to represent the keyword parameter, it is a dict. And when using both *args and **kwargs, you must *args the parameter columns before **kwargs, such as foo (a=1, b= ' 2′, c=3, a ', 1, None,), which prompts for syntax errors "SyntaxError: Non-keyword arg after keyword arg ".

For example, use the **kwargs variable parameter to create a dictionary:

def kw_dict (**kwargs):
Return Kwargs

Then the effect of the function defines a dictionary, kw_dict (a=1,b=2,c=3) and {' A ': 1, ' B ': 2, ' C ': 3} is equivalent.

Python's variable parameters are also called dynamic parameters, and look at the simple basic usage of *args and **kwargs.


def alias (*args, **kwargs):
Print (' args= ', args)
Print (' kwargs= ', Kwargs)

Alias (3, 3, 3,a= ' Hello ', b=3,c= ' C ')

The operation effect is as follows:

Tantengdemacbook-pro:learn-python tanteng$ Python3 args_kwargs.py
Args= (3, 23, 3, 3)
kwargs= {' A ': ' Hello ', ' B ': 3, ' C ': ' C '}
Args output is Tupple Ganso, Kwargs is a dictionary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.