The *args and **kwargs usage of Python3 advanced

Source: Internet
Author: User
Tags naming convention

*args and **kwargs are primarily used for function definitions. You can pass an indefinite number of arguments to a function. The indefinite meaning is: in advance do not know, the function user will pass the number of parameters to you, so in this scenario use these two keywords.  In fact, it is not necessary to write *args and **kwargs. * (asterisk) is required. You can also write *ar and **k. and written *args and **kwargs is just a popular naming convention.

There are two ways that Python functions pass parameters:
positional parameters (positional argument)
keyword parameters (keyword argument)

The difference between *args and **kwargs, both of which are mutable parameters in Python.
*args represents any number of nameless parameters, which are essentially a tuple;
**kwargs represents a keyword parameter, which is essentially a dict;

If you use both *args and **kwargs, you must *args the parameter column before **kwargs.

Example 1.

def fun (*args,**kwargs):

Print (' args= ', args)

Print (' kwargs= ', Kwargs)

Fun (1,2,3,4,a= ' A ', b= ' B ', c= ' C ', d= ' D ')

Output:

Args= (1, 2, 3, 4)

kwargs= {' A ': ' A ', ' B ': ' B ', ' C ': ' C ', ' d ': ' d '}

Example 2:

def mutil (Name,*ar):
Print (name, "Master, hello")
For item in AR:
Print ("My name is:", item)

Mutil ("Liuhu", "Xiaoyun", "Liuwei")
# Hello, Master Liuhu.
# My name is: Xiaoyun
# My name is: Liuwei

Example 3:
def Love (**kwargs):
For Key,value in Kwargs.items ():
Print ("{0} loves {1}". Format (Key,value))
Love (name= "Liuhu", age=18)
# name in love with Liuhu
# Age in love with 18


Example 4:
def test (arg1, Arg2, ARG3):
Print ("Arg1:", arg1)
Print ("Arg2:", arg2)
Print ("Arg3:", Arg3)

args = ("Both", 3, 5)
Test (*args)
Kwargs = {"Arg3": 3, "arg2": "A", "Arg1": 5}
Test (**kwargs)
# Arg1:two
# Arg2:3
# Arg3:5

# Arg1:5
# Arg2:two
# Arg3:3


The *args and **kwargs usage of Python3 advanced

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.