Python parameter combination, python Parameter

Source: Internet
Author: User

Python parameter combination, python Parameter

The order of parameter definitions must be: ① mandatory parameter, ② default parameter, ③ optional parameter, ④ name keyword parameter, ⑤ keyword Parameter

1 # a and B are mandatory parameters; c is the default parameter; args is a variable parameter; kw is the keyword parameter 2 def f1 (a, B, c = 0, * args, ** kw): 3 print ('a = ',' B = ', B, 'c =', 'args = ', args, 'kw =', kw) 4 5 # The sequence of parameter definitions must be: mandatory parameter, default parameter, optional parameter, naming keyword parameter, keyword parameter 6 def f2 (a, B, c = 0 ,*, d, ** kw): 7 print ('a = ',' B = ', B, 'c =', 'd = ', d, 'kw = ', kw)

Call

f1(1,2)f1(1,2,3)f1(1,2,c=3)f1(1,2,3,'a','b')f1(1,2,3,'a','b',x=99,y=88,z=77,t='100')f2(1, 2, city='Shanghai', ext=None)

Call result

a= 1 b= 2 c= 0 args= () kw= {}a= 1 b= 2 c= 3 args= () kw= {}a= 1 b= 2 c= 3 args= () kw= {}a= 1 b= 2 c= 3 args= ('a', 'b') kw= {}a= 1 b= 2 c= 3 args= ('a', 'b') kw= {'x': 99, 'y': 88, 'z': 77, 't': '100'}a= 1 b= 2 c= 0 city= Shanghai kw= {'ext': None}

Input with list or dict Parameters

args=(1,2,3,4)kw={'Nation':'China','City':'Shanghai'}f1(*args,**kw)args=(1,2,3)kw={'y':33,'city':'Shanghai'}f2(*args,**kw)

Result

a= 1 b= 2 c= 3 args= (4,) kw= {'City': 'Shanghai', 'Nation': 'China'}a= 1 b= 2 c= 3 city= Shanghai kw= {'y': 33}

Therefore, for any functionfunc(*args, **kw)It is called, no matter how its parameters are defined.

 

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.