Python function parameter *args**kwargs usage instance

Source: Internet
Author: User
The code is as follows:


#coding =utf8
__author__ = ' Administrator '

# *args and **kwargs can be used when the parameters of the function are not deterministic. *args no key value, **kwargs has a key value

def Fun_var_args (Farg, *args):
print ' args: ', farg
For value in args:
print ' Another arg: ', value

# *args can be used as a list or tuple that can accommodate multiple variables
Fun_var_args (1, ' both ', 3, None)

#args: 1
#another Arg:two
#another Arg:3
#another Arg:none


def Fun_var_kwargs (Farg, **kwargs):
print ' args: ', farg
For key in Kwargs:
print ' Another keyword arg:%s:%s '% (key, Kwargs[key])

# MYARG1,MYARG2 and Myarg3 are considered key, feeling that **kwargs can be used to accommodate multiple keys and value dictionary
Fun_var_kwargs (1, myarg1= ' both ', myarg2=3, Myarg3=none)
Output
#args: 1
#another keyword Arg:myarg1:two
#another keyword Arg:myarg2:3
#another keyword Arg:myarg3:None

def Fun_args (Arg1, Arg2, ARG3):
print ' arg1: ', arg1
print ' arg2: ', arg2
print ' Arg3: ', Arg3

Myargs = [' 1 ', ' both ', None] # definition List
Fun_args (*myargs)

Output
#arg1:1
#arg2:
#arg3: None

Mykwargs = {' arg1 ': ' 1 ', ' arg2 ': ' Both ', ' Arg3 ': None} # defines the dictionary type
Fun_args (**mykwargs)

Output
#arg1:1
#arg2:
#arg3: None

# both have
def Fun_args_kwargs (*args, **kwargs):
print ' args: ', args
print ' Kwargs: ', Kwargs


args = [1, 2, 3, 4]
Kwargs = {' name ': ' Beginman ', ' age ': 22}
Fun_args_kwargs (Args,kwargs)
# args: ([1, 2, 3, 4], {' Age ': $, ' name ': ' Beginman '})
# Kwargs: {}

Fun_args_kwargs (1,2,3,a=100)
#args: (1, 2, 3)
#kwargs: {' A ': 100}

Fun_args_kwargs (* (1,2,3,4), **{' a ': None})
#args: (1, 2, 3, 4)
#kwargs: {' A ': None}



  • 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.