18 Python - function definition parameters

12 function definition parameters

01 function

(1) Definition:

  def function name (parameter 1, parameter 2 ......):

                Function body

         return result

(2) call:

  Function name (actual parameter)

(3) function operates:

       Maximize code reuse,

  The minimum redundancy code,

  Decomposition process

(4) function parameter and return value

  Example 1: parameter argument

  def learning(name, course, start, end):

       print ( '{} k Registration Course: "{}"'. format (name, course))

       print ( '{} from all of the learning section {}' .format (start, end))

       print ( '{} exit Learning' .format (name))

   learning ( 'Tom', 'Python entry', 1, 3)

  result

  Tom registration k courses: "Python Getting Started"

  1 are learning from Section 3

  Tom quit learning

 

  Examples 2: return Return Value

   def add_number(x, y):

       result = x+y

       return result

 

   print(add_number(3, 5))

  result

  8

 

  Example 3: + return arguments parameter

  def intersect(seq1, seq2):

      res = []

      for k in seq1:

          if k in seq2:

              res.append(k)

      return res

 

  s1 = 'uk.cc'

  s2 = 'youpingketang.com'

  l = intersect(s1, s2)

  print(l)

 

   ['u', 'k', '.', 'c', 'c']

 

(5) Summary

  Defining a function, the function name and the determined number of parameters;

  If necessary, you can do checks on the data type of the parameter;

  The functions that can be used returnat any time to return a function result;

  Function completes nor returnwhen statements automatically return None.

  Function can return multiple values ​​simultaneously, but in fact is a tuple.

 

02 function variable scope (scoping)

(1) the scope of classification

  Python, variables in the program is not in any position that can be accessed, access depends on where the variable is assigned.

  Scope of a variable determines which part of a program in which a particular variable name can be accessed. Python's scope, a total of four kinds, namely:

  • L (Local) local scope
  • E (Enclosing) function outside the closure function
  • G (Global) global scope
  • B (Built-in) built scope (where the scope of the built-in function module)
(2) the scope of the search order - no special circumstances, the principle of proximity

  To L -> E -> G - Rules> B lookup, namely: not found locally, will find a local (e.g., closure) to the outer partial, you will not find to find the global, addition to built-in look.

  example:

  g_count = 0 # global scope

  def outer():

      o_count = 1 # functions outer closure function

      def inner():

          i_count = 2 # local scope

(3) inside which a predetermined variable scope

  Built-in scope is achieved by a standard module called builtin, but the variable name itself is not built into the scope, so must import the files before you can use it.

  In Python3.0, you can use the following code to see in the end what predefined variables:

  >>> import builtins

  >>> dir(builtins)

  ……

(4) Not all code blocks are scope

  Only Python module (Module1), class (class) and a function (def, lambda) before introducing a new scope, the other block of code (e.g., IF / elif / the else / , the try / the except , for / the while , etc.) We will not introduce new scope , that variable definitions of these statements can also be accessed externally, the following code:

  >>> if True:

  ...  msg = 'I am from Runoob'

  ...

  >>> msg

  'I am from Runoob'

  >>>

  Msg variable is defined in the example if block but still be accessible outside.

  If msg is defined in the function, then it is a local variable, not external access:

  >>> def test():

  ...     msg_inner = 'I am from Runoob'

  ...

  >>> msg_inner

  Traceback (most recent call last):

    File "<stdin>", line 1, in <module>

  NameError: name 'msg_inner' is not defined

  >>>

  From the point of view of information being given, it explained msg_inner not defined, can not be used because it is a local variable, can be used only within the function.

(5) Internal modify the scope of external variables --global keyword

  When you want to modify the scope of internal variables outer scope, it is necessary to use a global and nonlocal keyword.

  The following examples modify global variables num:

   

  Examples of the above output:

  1
  123
  123
(6) modify nested scopes --nonlocal keyword

  To modify nested scopes (the enclosing scope, the outer non-global scope) variables nonlocal keyword is required, as the following examples:

   

 

  Examples of the above output:

  100
  100

 

03 parameter passing

  In python, belong to the object type, the variable type is not:

  a=[1,2,3]
  a="Runoob"

  Above, the [1,2,3]  type List, "Runoob"  type String,

  The variable is not a type, she is just an object reference (a pointer), may be pointing to an object of type List, it can be pointed objects of type String.

(1) can be changed (mutable) and can not be changed (immutable) objects

  In python, strings, tuples, and the numbers are not subject to change,

  The list, dict and so it can be modified objects.

  • · Immutable: Variable Assignment  a = 5  then the assignment  a = 10 , the actual value of the new object 10 to generate an int Here, let a point to it, and 5 are dropped, instead of changing the value of a, is newly equivalent a.
  • · Variable Type: Variable Assignment  la = [1,2,3,4]  then assigned  la [2] = 5  third element values change sucked List la, la in itself did not move, only part of its internal value is modified.

Python parameter transfer function:

  • · Immutable: similarity value passed c ++, such as integer, string, a tuple. The value Fun (a), only a transfer of a subject itself has no effect. Such modifications (a) an internal value of a fun, but modify the object copied to another, does not affect a per se.
  • · Variable type: Similar c ++ are passed by reference, such as lists, dictionaries. As fun (la), sucked la real pass in the past, the revised fun outside la also be affected

  python, everything is an object, we can not say the strict sense of the value passed by reference or pass, we should say pass immutable objects and pass variable objects.

(2) python mass immutable object instance

   

 

  Example 2 There are int objects, point B which is variable,

  When the time is passed to the function ChangeInt copy variable b, a and b values ​​are transmitted by way point to the same Int object, a = 10, then generate a new int value object 10, and let a point to it.

(3) python object instance variable transmission

  Mutable objects modify the parameters in the function, then the function call this function, the original parameters have been changed. E.g:

   

  Passed into the function and add new content at the end of the object is the same with a reference. So the output results are as follows:

  The function values: [10, 20, 30, [1, 2, 3, 4]]
  External function values: [10, 20, 30, [1, 2, 3, 4]]

 

(4) python variable transmission and immutable type (Other Notes)

  By default, our actual value of the variable or function is passed in time to see what type it is

  A class can change the list of dictionary table. Type variable transmission, a reference delivery address, the operation may affect the function of the original value. If you do not want to change the copy can be passed.

  A class can not be changed: integer, floating point, string, Tuple. Transmitting immutable type, to transfer a copy function, the function does not affect the operation of the original value

  ①      transfer immutable type

  

   result  

 

View memory address x

 

 

  The reason: plastic can not be changed,

    ② x = 5 is an integer,

    ③ When the x passed to a function, x = 5 is copied out a new transmission itself has not changed

    ④ so the first printing and the second printing is the original version of x = 5

② transfer variable type

 

③ variable transmission types - without changing the original

Method a: Copies --copy ()

    

Method two: passing all values ​​L [:]

     

 

04 parameters

(1) Parameter type

  Python function definition is very simple, but the flexibility is very large. In addition to the normal definition of a mandatory parameter , you can also use the default parameters, variable parameters and keyword parameters , the function interface definitions such that it not only can handle complex parameters, may also simplify the code of the caller.

  The following is the formal parameter type can be used when calling the function:

    •   Required parameters
    •   Keyword arguments
    •   The default parameters
    •   Variable-length parameters
(2) position parameter

  Example: Calculation X n-

  def power(x, n):

      s = 1

      while n > 0:

          n = n - 1

          s = s * x

      return s

  For power (x, n) after the modification function, any of n-th power can be calculated:

  >>> power(5, 2)

  25

  >>> power(5, 3)

  125

  Power (x, n) after modification function has two parameters: x and n, these two parameters are position parameters, the function is called, passing the two values, according to the order assigned to the position parameters x and n- .

(3) the default parameters
① the introduction of default parameters

  Since we often calculate X 2 , therefore, we can bring a second default value of the parameter n is set to 2:

 

 

       For n > 2other cases, you must explicitly pass n, for example power(5, 3).

② Notes

  When you set the default parameters, there are several points to note:

  One is a mandatory parameter in front, after the default parameters , otherwise the Python interpreter will complain (think about why the default parameters can not be placed in front of mandatory parameters);

  The second is how to set the default parameters.

  When the function has a plurality of parameters, the parameters placed in front of a large change, a small change in the parameters put back. Small changes in parameters can be used as the default parameters.

③ the benefits of using the default parameters

  What are the benefits of using the default parameters? The greatest advantage is difficult to reduce the function was called.

 

 

④ multiple parameters to call the default order

  A plurality of default parameters, time of the call, the default parameters may be provided in order, such as call enroll ( 'Bob', 'M', 7), meaning that, in addition to the name, gender these two parameters, the last one parameters used in the parameters age, city Since no parameters, still use the default value.

  Order may not provide some default parameters. When not in order to provide some default parameters, parameter names need to write. Like calling enroll ( 'Adam', 'M', city = 'Tianjin'), meaning that, city pass in parameters values, other default parameters continue to use default values.

⑤ default parameters of the pit - default parameter must point to the same objects!

  The default parameters have the biggest pit, demonstrate the following:

                             

 

 

 

  Many beginners are confused, default parameters are [], but it seems every function "remember" the last to add a list 'END' post.

  The reason is explained as follows:

  When Python functions defined, the default value of the parameter L was calculated out, i.e., [], because the default parameter L is also a variable that points to the object [], every time the function is called, if L is changed content, the next call, the default parameters are changed, no longer a function definition [] a.

   Define default parameters to keep in mind one thing: the default parameters must point to the same objects!

 

 

 

(4) Variable parameters

  Variable parameters allow you pass 0 or any number of parameters, these variable parameters are automatically assembled into a tuple in the function call.

 ① no variable parameters before

 

 

② with variable parameters defined *

 

 

  Define a variable parameter definitions and parameter list or tuple compared, only adding a parameter in the previous *number. Inside the function, the parameter numbersreceived is a tuple, and therefore, the function code is completely intact. However, when you call the function, you can pass any number of parameters, including 0 parameter calc ():

 

③ how the incoming tuple or list or in front of the variable parameter tuple --list transfer add *

  Python allows you add a tuple in a list or in front of *numbers, or a list with a tuple element becomes pass in variable parameter:

 

 

 

(5) keyword arguments
the introduction of key parameters - (1) ** kw (2 ) kv to

  Keyword parameter allows you pass 0 or any number of parameters including the parameter name, these keyword parameters are automatically assembled into a dict inside the function.

   

 

 

② keyword arguments benefits - expansion function, more acceptable parameters such as registration scene

  Keyword arguments What is the use? It can extend functions . For example, in persona function, we can guarantee received nameand agethese two parameters, however, if the caller is willing to provide additional parameters, we can receive.

  Register scenario: Imagine you're making a user registration function , in addition to user name and age are required, other options are available, use keyword parameters to define the function will be able to meet the registration requirements.

 

③ how to pass a keyword argument dict - with **

 

 

  **extraIt represents the extrakey-value keyword arguments passed to use all functions of this dict **kwparameter kwwill get a dict,

  Note kwobtained dict is extraa copy of kwthe changes will not affect the function of the outside extra.

 

(6) named keyword arguments

Slightly, there is time to add

(Reference https://www.liaoxuefeng.com/wiki/1016959663602400/1017261630425888 )

 

 

(7) a combination of parameters

  Defined in the function Python, can be a mandatory parameter, default parameter, the variable parameter, keywords and named keyword parameters, these five parameters can be used in combination

  Note, however, the order of the parameters must be defined: mandatory parameters, default parameters, variable parameter, named keyword arguments and keyword arguments.

       Although a combination of up to five parameters, but do not use too many combinations, or poor intelligibility function interface.

(Reference https://www.liaoxuefeng.com/wiki/1016959663602400/1017261630425888 )

(8) Summary

  (From https://www.liaoxuefeng.com/wiki/1016959663602400/1017261630425888 )

  Python functions have very flexible parametric form, either simple call, and can pass very complex parameters.

  The default parameter must use immutable objects, if the object is variable, there will be a logical error when the program is running!

 

  Pay attention to the definition of variable parameters and keyword arguments syntax:

  *argsIt is a variable parameter, args a tuple is received;

  **kwKeyword parameters, kw received a dict.

  And how to pass variable parameters and keyword arguments when calling function syntax:

  Variable parameters can be passed directly: func(1, 2, 3), but also to the assembly list or tuple, and through *argsIncoming: func(*(1, 2, 3));

  Keyword parameters can be passed directly: func(a=1, b=2), but also to assemble dict, and then through the **kwpass: func(**{'a': 1, 'b': 2}).

  Use *argsand **kwis the habit of writing Python, of course, you can also use other parameter name, but the best use of idioms.

 

  Named keyword arguments to limit the caller can pass the parameter name, and can provide default values.

  Define named keyword arguments in the absence of the variable parameters of the case do not forget to write delimiters *, it would be otherwise defined position parameters.

Guess you like

Origin www.cnblogs.com/yijiexi/p/11139496.html