Python variable length parameters

Source: Internet
Author: User

The list of function parameters defined in Python can be amazing, mainly including variable parameters with non-Keyword variables and keywords.

Variable Length Parameter

First, we define the following functions:

def tuple_var_args(arg1,arg2='default arg2',*vargs_tuple):    print 'format arg1:',arg1    print 'format arg2:',arg2    for arg in vargs_tuple:        print 'another arg:',arg

Then you can call it as follows:

Substring ('arg1') tuple_var_args ('arg1', 'arg2') tuple_var_args ('arg1', arg2 = 'arg2') tuple_var_args ('arg1', 'arg2 ', 'arg3') tuple_var_args ('arg1', 'arg2', * ('arg3 ',))
Tuple_var_args ('arg1', * ('arg3',) # Here arg3 is passed to arg2


Keyword variable parameters

First, define the following functions:

def dict_var_args(arg1,arg2='default arg2',**vargsd):    print 'format arg1:',arg1    print 'format arg2:',arg2    for arg in vargsd:        print 'another arg:',arg
The call method is as follows:

dict_var_args('arg1')dict_var_args('arg1','arg2')dict_var_args('arg1',arg2='arg2')dict_var_args('arg1','arg2',arg3='arg3')dict_var_args('arg1',arg3='arg3')dict_var_args(1,**{'foo':4,'bar':5}) dict_var_args(**{'arg1':1,'foo':4,'bar':5})

Hybrid use

Define the following functions

def tuple_dict_var_args(arg1,arg2='default arg2',*tuple_args,**vargsd):    print 'format arg1:',arg1    print 'format arg2:',arg2    for t_arg in tuple_args:        print 'another no-key arg:',t_arg    for arg in vargsd:        print 'another key arg:',arg

The call method is as follows:

Tuple_dict_var_args (, 5) #3, 4, 5 pass to * tuple_arstuple_dict_var_args (1, * (,), a = 1, B = 2) tuple_dict_var_args, * (,), ** {'A': 'A', 'B': 'B '})


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.