Parameters in Python

Source: Internet
Author: User

Define a function in Python, you can use required parameters, default parameters, variable parameters, and keyword parameters, all 4 parameters can be used together, or only some of them, but note that

The order of the parameter definitions must be: required, default, variable, and keyword parameters .

Take a look at the example code:

defFunc (a,b,c=0,*args,**kw):Print 'a='A'b='B'c='C'args=', args,'kw=', KW>>> func () A= 1 b= 2 c= 0 args= () kw= {}>>> func (All) A= 1 b= 2 c= 3 args= () kw= {}>>> func (1,2,4, (1,3,4,5)) a= 1 b= 2 c= 4 args= ((1, 3, 4, 5), kw= {}>>> func (1,2,4,11,22,33,44,55) A= 1 b= 2 c= 4 args= (one, one, one, one, one) kw= {}>>> func (1,2,4,11,22,33,44,55,{'x':'xx','y':'yy'}) a= 1 b= 2 c= 4 args= (11, 22, 33, 44, 55, {'y':'yy','x':'xx'}) kw= {}>>> func (1,2,4,11,22,33,44,55,x='xx', y='yy') A= 1 b= 2 c= 4 args= (one, one, one, one, one) kw= {'y':'yy','x':'xx'}

#you can write it like that.defFunc (a,b,c=0,*args,**kw):Print 'a='A'b='B'c='. cn'args=', args,'kw=', Kwargs= (1, 2, 3, 4) kw= {'x': 99}func (1,2,4,*args, * *kw) a= 2 b= 3 c= 4 args= (5, 6, 7, 8) kw= {'y': 100,'x': 99}

Summarize:

Be aware of the syntax for defining mutable parameters and keyword parameters:

*argsis a variable parameter, and args receives a tuple;

**kwis a keyword parameter, kw receives a dict.

And how to pass in the syntax for variable and keyword arguments when calling a function:

Variable parameters can be directly passed func(1, 2, 3) in:, you can first assemble a list or a tuple, and then pass in *args : func(*(1, 2, 3)) ;

Keyword parameters can be directly passed in: func(a=1, b=2) , you can first assemble dict, and then pass in **kw : func(**{‘a‘: 1, ‘b‘: 2}) .

 

Parameters in Python

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.