Python function parameter * args ** kwargs usage example

Source: Internet
Author: User

Copy codeThe Code is as follows:
# Coding = utf8
_ Author _ = 'admin'

# When the parameters of a function are unknown, you can use * args and ** kwargs. * Args has 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 consisting of multiple variables.
Fun_var_args (1, 'two', 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 as keys. ** kwargs can be considered as a dictionary that can hold multiple keys and values.
Fun_var_kwargs (1, myarg1 = 'two', 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', 'two', None] # definition list
Fun_args (* myargs)

# Output:
# Arg1: 1
# Arg2: two
# Arg3: None

Mykwargs = {'arg1': '1', 'arg2': 'two', 'arg3': None} # define the dictionary type
Fun_args (** mykwargs)

# Output:
# Arg1: 1
# Arg2: two
# 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': 22, '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}


 

 

Related Article

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.