Python function parameter passing mechanism

Source: Internet
Author: User
Tags function definition

Recently, in the process of writing code, we found that the Python parameter passing is not very clear. Python is really flexible, but the consequence of flexibility is that it takes more time to study. Don't say much, start めましょう!!!


There are several ways to pass the Python parameter:

1: Position parameter

Fun (Arg1,arg2,...)

2: Default value parameter

Fun (arg1,arg2=<value> ...)

3: Keyword parameter

Fun (arg1=<value>,arg2=<value> ...)

4: Excess Position parameter

Fun (ARG1,ARG2,*ARG3)

5: Excess keyword parameter

Fun (ARG1,ARG2,**ARG3)

6: Mixed parameters

Fun (ARG1,ARG2=<VALUE>,*ARG3,**ARG4)


One: Positional parameters

Fun (Arg1,arg2,...)

Positional parameters are basic in all development languages, this way the function declares a few parameters, it must pass several parameters at the time of invocation, and the position of the passed parameter must be consistent with the argument position of the declaring function.

in [+]: def demo (A, B): ....: Return a+b ....: in []: Demo (1)--------------------------------------------------- ------------------------TypeError Traceback (most recent) <IPYTHON-INPUT-65-CD 1a36a59e96> in <module> ()----> 1 demo (1) Typeerror:demo () takes exactly 2 arguments (1 given) in [+]: Demo ( ) out[66]: 3In [67]:

This method is relatively simple, do not do too much explanation.



Second: Default value delivery

Fun (arg1,arg2=<value> ...)

I personally think that it is better to combine the default value passing with the Third keyword pass, because in most cases the default value is passed by itself using the keyword.

in [67]: def demo (a,b=2):   ....:      return a+b   ....: in [68]: demo (2) Out[68]:  4in [69]: demo (4,5) Out[69]: 9in [70]: demo (a=4) Out[70]: 6in [71]: demo (a=4,b=5) Out[71]: 9in [72]: demo (b=5)------------------------------------------------------------------- --------typeerror                                   traceback  (most recent call last) <ipython-input-72-f88a17b9de38> in < Module> ()----> 1 demo (b=5) Typeerror: demo ()  takes at least 1  argument  (1 given) In [73]: demo (b=5,a=3) out[73]: 8 

When declaring the function demo, the parameter B is paid a default value of 2, so when you call the demo, you can just pass it to a, and the default value of B is used when calculating inside the function.

If you pass a value to B at the time of the call, use the passed value instead of the default value.

However, in this case, the parameter A is required, so the call must be given a value, otherwise it will be an error. Because parameter B has a default value, it is possible to use the default value even if the value is not passed to B.

When declaring a function, the parameter list has the name of the parameter, so the parameter can be passed by specifying the name of the variable, and the position of the variable can be changed so that the inside of the python itself will go to which parameter to which the argument should be passed.


Three: Keyword delivery

Fun (arg1=<value>,arg2=<value> ...)

in [+]: def demo (a=1,b=2,c=3): ....: Return a+b+c ....: in [Bayi]: Demo (4,5,6) out[81]: 15In []: Demo (4) out[82]: 9 In [8In]: Demo (b=4) out[83]: [up]: Demo (b=8,a=5,c=3) out[84]: 16

It's easy to understand the way the default value is passed, and it's easier to see the keyword passing, so it's not too much to explain.


Four: Excess position parameters

Fun (ARG1,ARG2,*ARG3)

In [94]: def demo (A,b,*args):    ....:     print a+ B   ....:     print type (args)    ....:      print args   ....:     in [95]: demo ( 1,2,3,4,5) 3<type  ' tuple ' > (3, 4, 5) In [100]: demo (all in all) 3<type  ' tuple ' > (3,) In [98]: demo (1,23) 24<type  ' tuple ' > () In [101]: demo (1)----------------- ----------------------------------------------------------typeerror                                   Traceback  (Most recent call last) < Ipython-input-101-cd1a36a59e96> in <module> ()----> 1 demo (1) TypeError:  Demo ()  takes at least 2 arguments  (1 given) 

As shown in the code above: in the declared function demo, parameters A and B are required, so a and B are necessary, that is, when the demo function is called, at least two parameters must be passed, otherwise an error will occur.

The excess positional parameters use the asterisk (*) plus the variable name (*args), in passing the extra 2 parameters, the first two parameters are assigned to a and B, the following parameters will be the whole assignment to args, by printing can be seen, args is a primitive type, So you can use it by traversing the data inside it.


Five: Excess keyword parameters

Fun (ARG1,ARG2,**ARG3)

In [103]: def demo (A,b,**kwargs):    .....:     print  a+b   .....:     print type (Kwargs)   &nbsp ...:      print kwargs   .....:     in [ 104]: demo 3<type  ' dict ' >{}in [105]: demo (1,2,c=1) 3<type  ' dict ' >{' C ':  1}in [106]: demo (1,2,c=1,d=2) 3<type  ' dict ' >{' C ': 1,  ' d ':  2}In [ 107]: demo (1,2,3,c=1,d=2)--------------------------------------------------------------------------- typeerror                                   traceback  (most recent call last) <ipython-input-107-94e09001d957> in < Module> ()----> 1 d Emo (1,2,3,c=1,d=2) Typeerror: demo ()  takes exactly 2 arguments  (5 given) in  [108]: demo (---------------------------------------------------------------------------) typeerror                                   traceback  (most recent call last) <ipython-input-108-856c09b109ab> in < Module> ()----> 1 demo (a) Typeerror: demo ()  takes exactly 2  arguments  (3 given)

Excess keywords use two asterisk plus variable name, i.e. (**kwargs)

In the previous introduction of the keyword parameters can be seen, the key parameters are generally in the form of key-value pairs, in excess of the keyword parameter is also, Kwargs only accept the parameters of key-value pairs, so like 107 and 108, the two methods of invocation will be error, values 1 and 2 are assigned to A and B, the back of the c= 1 and d=2 through Kwargs to accept, the remaining 3 no formal parameters to accept, so will be error. Because the **kwargs value accepts the parameter of the key-value pair form.


Six: Mixed parameters

Fun (ARG1,ARG2=<VALUE>,*ARG3,**ARG4)

In [109]: def demo (A,b,c=1,*args,**kwargs): ...: Print a+b+c ....: Print args ....: Print Kwargs. ....: in [+]: Demo (2,3) 6 () {}in [111]: Demo (2,3,4) 9 () {}in []: Demo (2,3,4,5) 9 (5,) {}in [113]: Demo (2,3,4,5,6) 9 (5, 6) {}in []: Demo (2,3,4,5,6,d=1,e=2) 9 (5, 6) {' E ': 2, ' d ': 1}

As shown in the code above, mixed parameters are used in conjunction with the several forms described earlier.

A and B are positional parameters, C is the default value parameter, args is an excess positional parameter, and Kwargs is an excess keyword parameter.

Understand the above mentioned several forms, then to understand the mixed parameter form should be relatively simple, do not do too much explanation.


The following is a mixture of instances of the form, explain the specific use.

First define the function as follows

In [109]: def demo (A,b,c=1,*args,**kwargs): ...: Print a+b+c ....: Print args ....: Print Kwargs. ....:


Example 1:

in [+]: Demo (2)---------------------------------------------------------------------------TypeError Traceback (most recent) <ipython-input-115-5fc919890c38> in <module> ()----> 1 demo (2) T Ypeerror:demo () takes at least 2 arguments (1 given)

When the function is called only a value is passed, but from the function definition, A and B must, only a value is passed, the equivalent of only a assigned value, B is not assigned, so will error.


Example 2

In [117]: Demo (2,3,a=4)---------------------------------------------------------------------------TypeError Traceback (most recent) <ipython-input-117-803c2126718d> in <module> ()----> 1 de Mo (2,3,a=4) Typeerror:demo () got multiple values for keyword argument ' a '

The reason why the above call function error is because it is not in the correct order to assign a value to the demo, can not be considered to specify a=4, will be called when the 4 assigned to a, the remaining two values 2 and 3 are assigned to B and C, which is wrong, in this mixed mode, the assignment order must be the first position parameter, The excess keyword parameter, which is the default value parameter, and excessive positional parameters, or an error occurs. Let's look at the following example.

In [119]: Demo (1,2,3,d=2,5,6) File ' <ipython-input-119-6a415509517c> ', Line 1 demo (1,2,3,d=2,5,6) Syntaxerror:no N-keyword arg after keyword Argin [+]: Demo (1,2,3,5,6,d=2,) 6 (5, 6) {' d ': 2}

The three-way assignment to the a,b,c, this is no problem, but the d=2 over the keyword parameter in the 5, 6 over the position parameter before the error occurred, the order of the two to exchange a bit there is no problem.


Redefine the function demo, after which the instance will use the newly defined function

In [121]: def demo (a,b,c): ....: Return a+b+c ...


Example 3

In [122]: Demo (a=1,2,3) File ' <ipython-input-122-ec666e77af79> ', Line 1 demo (a=1,2,3) Syntaxerror:non-keyword ar G after keyword Argin [123]: Demo (1,2,c=3) out[123]: 6In [124]: Demo (a=1,b=2,c=3) out[124]: 6

As shown in the code above:

[122] in the Call function demo when the first specified a value, an error occurred, the error message translated into Chinese means: Do not use positional parameters after the keyword parameter.

[123] The call method does not have an error. Therefore, when calling a function, it is important to use the keyword form to pass the parameter after the location.


Example 4

In [the]: args = (2,3) in [126]: Demo (1,*args) out[126]: 6In [127]: Demo (A=1,*args)-------------------------------------- -------------------------------------TypeError Traceback (most recent) <ipytho N-input-127-aeb489dc72f3> in <module> ()----> 1 demo (A=1,*args) Typeerror:demo () got multiple values for Keyword argument ' a '

above [126] when called, through a meta-ancestor wrapped 2 parameter values, 1 assigned to parameter A, Ganso args in the 2,3 respectively assigned to the parameters B and C.

However, [127] The invocation form will be error, its invocation form can be seen as demo (a=1,2,3), the reason is similar to the case 3 above, because the Python " key form parameter must be at the back of the location ," So python at the time of assignment, The above error message occurs when you assign a value of 2 to a, assign a value of 3 to B, and finally assign the a=1 to a.


If a different form of the parameter is passed, and 2 and 3 are loaded into the dictionary, there will be no such error, as shown in the following code

In [129]: dict={' B ': 2, ' C ': 3}in [6In]: Demo (a=1,**dict) out[130]: [131]: Demo (**dict,a=1) File "< Ipython-input-131-cd33424dd41b> ", Line 1 demo (**dict,a=1) ^syntaxerror:invalid syntax

Wrapping parameters in a dictionary is equivalent to all parameters being passed in the form of a keyword parameter, the demo (a=1,b=2,c=3), so there is no error.


In summary, when passing parameters, be sure to follow the order of the parameters passed, that is, the location parameter, the default parameter, the excess position parameter, and excess keyword parameters .

This article is from the "ssspure" blog, make sure to keep this source http://ssspure.blog.51cto.com/8624394/1759835

Python function parameter passing mechanism

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.