Part IV function basis

Part IV function basis

The definition of a function

Function is a function with tools, tools will be ready in advance is defined functions encountered scenarios brought on by the function is invoked,

Function role

  1. Lengthy settlement procedures
  2. Scalability poor settlement procedures
  3. Poor readability settlement procedures

Defined functions:

Use function must follow the 'definition of first, after calling' principle. (Function definition stage, only detect syntax, the system does not perform the function of the code)

定义函数的语法
def 函数名(参数1 参数2...):
    """文档描述"""
    函数体
    return 值
  1. def: keyword-defined functions;
  2. Function name: function name memory function points to address, is the function body code references the function name should reflect the performance function.
  3. Parentheses: defining parameters in brackets, the parameter is optional, and need not specify the type parameter;
  4. Colon: after the brackets to add a colon, and then start the next line indented code written in the function body;
  5. "" "Document describes" "": description of the function function parameters introduced document information such as non-essential, but it is recommended together to enhance the readability of the function;
  6. Function body: the composition of the statements and expressions;
  7. return value: Return value defined function, return is dispensable.
  8. pass: What is the function of the representative body do not pass, empty function called for early writing programs to build architecture.

Three forms two functions defined

  1. No-argument function:

    When you define a function parameter is a function of the body receives external media by value, in fact, not a variable name in the function parameter brackets stage, called the no-argument function should be noted that: no arguments when the meaning of the call when the function is also need to pass parameters.

    If the function does not need to rely on an external body of the incoming code logic value, you have to be defined as a function of no arguments.

  2. There are function parameters

    There are brackets in the function parameter definition phase, called parametric function has to be noted that: there are parameters defining means when you call must also pass parameters.

    If the function code logic relies on the external body of the incoming values, there have to be defined as a function parameter.

  3. Empty function

    When you know you need to achieve a certain function, but do not know how to code. Temporarily write an empty function, and then to perform other functions. (Pass)

Three function return value

return:

return function is a sign of the end, there can be multiple return within a function, to return as long as the execution, the function will be executed

return return value can return any data type

The number of non-return return value limitations, may be used to return multiple values ​​separated by a comma

  1. 0: Return none
  2. 1: The return value is the value itself
  3. A plurality of: The return value is a tuple

Four function calls

The above talked about the function call Function name (...) that is calling the function, the function body executes the code until it has finished or return the code to perform the function body all over.

Function has finished running all the code, if the function body do not write return, none will be returned

Three types of function calls

def max_self(x, y):
    if x>y:
        return x
    eles:
        return y
    
#1.
max_self(1,2)
#2
res = max_self(1,2)*12
#3
max_self(max_self(20000,30000),40000)

Five parameter function

Parameter argument function is divided into:

Parameter: Parameter i.e., by defining a function, the statement in parenthesis, parameters essentially a variable name, for receiving the transmitted external value.

Arguments: i.e., when calling the function, the incoming values ​​in parentheses, the value may be constant, variable, or a combination of three of expression.

There are parameters when calling function argument (value) will be assigned to the parameter (variable names). In python, the variable name and the value of simply binding relationship, and for the function, this is only binding relationship when the function call to take effect after the end of the call when released.

Positional parameters

Refers to the position parameter is a parameter defined order, need to see from two angles;

Location parameter:

When defining the function, in order from left to right in turn defined parameter, called the position parameter.

Any form parameter defined in this value must be transmitted.

Location argument:

When calling the function, definition of the order from left to right argument, argument called location,

All participants in this solid form parameter defined correspondence with the order from left to right shape.

Keyword arguments

When calling the function, according to the form of key = value passed as a parameter to the specified value, called Keyword argument

Features: You can break the limit position, but still for the specified parameter assignment.

note:

  1. You can mix position arguments and keyword arguments, but the location argument must be key arguments in the left
  2. Position and can be mixed arguments keyword arguments, but can not repeat the assignment for a parameter.

The default parameter

Features: During the definition phase has already been assigned, which means you can not assign a value when calling.

note:

  1. Location parameter must be placed in the default parameter left.
  2. The default parameter values ​​assigned once aimed at the definition phase, which means that the value of default parameters have been fixed in the function definition stage.
  3. The default value of the parameter should normally be immutable.

summary

Application of arguments: depending on personal habits

Application of the shape parameters:

  1. In most cases the value of the same call, the parameters should be defined as a location parameter
  2. In most cases the value of the same call, you should define the parameters to the default parameter

Six variable-length parameters

Variable-length parameters:

Refers to the function call, the number of parameters passed may not be fixed; the function is called, by value no more than two ways, one is the position of the argument, and the other argument is a keyword, thus parameter there must also be two solutions, in order to receive the overflow position arguments (*) with the keyword arguments (**)

* Length of the variable parameter:

形参中的*会将溢出的位置实参全部接收,然后存储元组的形式,然后元组赋值给*的参数.需要注意的是:*后的参数名约定俗成为args.

Variable-length argument of *:

实参中的*,*会将*后参数的值循环取出,打散成位置实参.以后但凡碰到实参中带*的,他就是位置实参,应该马上打散成位置实参去看.

** The variable length parameter:

形参中的**会将溢出的关键字实参全部接收,然后存储字典的形式,然后把字典赋值给**的参数.需要注意的是:**后的参数名约定俗成为kwargs.

The variable-length argument **:

实参中的**,**会将**后参数的值循环取出,打散成关键字实参.以后但凡碰到实参中带**的,他就是关键字实参,应该马上打散成关键字实参去看.

== == named key parameter:

In the function definition stage, the parameters are named after the * key parameters

Features: In the pass value must be passed in accordance with the value of key = value manner and key must be named keyword arguments specified parameter name.

Four features seven function object

  1. Quote

    x = 'hello nick'
    y = x 
    
    f = func
    print(f)
  2. As an argument to a function

    len(x)
    def foo(m):
        m()
    
    foo(func)
  3. It can be used as the return value of the function

    def foo(x):
        return x
    
    res = foo(func)
    print(res)
    res()
  4. It can be used as container type elements

    1 = [x]
    function_list = [func]
    function_list[0]()

Eight nested functions

Nested-defined function: the function defined within a function, the function can not be used outside the function defined inside.

Analogy: that is thrown into a pile of tools in the toolbox, and then want to get a tool, available directly from the toolbox on the line.

from math import pi 

def circle(radius, action='area'):
    def area():
        return pi * (radius**2)
    
    def perimeter():
        return 2*pi*radius
    if action == 'area':
        return area()
    else:
        return perimeter()
print(f"circle(10):{circle(10)}")
print(f"circle(10),action='perimeter'):
      {circle(10,action='perimeter')}")

Nine namespace and scope

Internal function defined functions can not be used inside a function defined in an external function; learning this section you will know why this happens.

Namespaces

Namespace definition: memory space binding relationship between a variable name and variable stored in memory, and this space is called a namespace.

  1. Built-in namespace:

    Built-in namespace: Store python interpreter that comes with the name, such as int, float, len

    Life cycle: when the interpreter started to take effect, fail when the interpreter is closed.

  2. Global namespace:

    In addition to the built-in and a local name, the rest are stored in the global namespace, the following code x, func, l, z

    Life cycle: when the file is executed into effect, expire after file execution

  3. The local name space (local name space):

    The local name space: the name of the function body for storing generated during a function call, such as the following code f2

    Life Cycle: take effect during the function call when the file is executed, expire after the function execution

  4. Load order:

    Since the .py file name is the built-in open space python interpreter loading end, began to open the file, this time will produce a global name space, but there is a certain time a function is called in the file will begin to produce local name space, so the load order for the namespace: built -> global -> partial

  5. Find the order:

    As the name space is used to store a binding relationship between the variable name and value, so whenever you want to find the name, it must be found in one of the three, look for the following order:

    Find the current location, location if the current location is the local name space, the search order to: Local -> Global -> Built-in

Scope

Domain refers to a region, i.e. the region scope of action.

  1. Global scope:

    Global effective, global survival, and includes built-in namespace global name space.

  2. The local scope:

    Local small, temporary storage, contains only the local name space.

  3. important point:

    Scope relations function definition stage fixed die, regardless of the function was called.

  4. The scope of application function object +

    def f1():
        def inner():
            print('from inner')
         return inner
    f =f1()
    
    def bar():
        d()
    bar()
    
    #from inner

== Notes ==

  1. In the local want to modify the global variable type, without any life, it can be modified directly.
  2. In the local immutable type if you want to modify global, the need to use global statement, declared as global variables can be modified directly.

Guess you like

Origin www.cnblogs.com/zhulipeng-1998/p/11728988.html