Python series of functions (b)

  • Nested functions

In the Python programming language, create another function (object because Python everything is an object, the object is actually a function) in the body of the function is perfectly legal, this function is called internal / nested functions.

example:

# Coding: UTF-. 8 
DEF outer (): 
    DEF Inner (): 
        Print ( "IS Inner Method,") 
    Print ( "Is outer Method,") 
    Inner () 

# call the outer function 
outer () 
# call outer () internal function , error 
# inner ()

operation result:

Is outer Method
is Inner Method

    When the inner () # call to inner (), there are mistakes
NameError: name 'inner' is not defined

  • Closure function

What is closure?

 If an internal function, the variables in the outer scope (not global scope) is referenced, then the internal function is considered to be closure (closure)

 He said the point is clear: Inside the function, reference is made free variables of the outer function

Packages are closed:

  • Save-shaped body function information, the local variable of the function information can be saved for the installation calculation, hidden is useful

  • In many GUI or API supports callback event-driven programming is also very useful

There are two ways to call closure:

  1. Called directly internally

  2. Returns the function name

eg

 1. Direct call internally

# - * - Coding: UTF-. 8 - * - 

DEF outer (name): 
    DEF Inner (name): 
        # name = "Mr.zhang" where # name value overrides the following outer calling function arguments, which is directed range variable function scope 
        print ( "Sub Method:% S"% name) 
        # __closuer__ used to determine whether the built-in property is a closure, the return address, is returned None, the closure function not 
        print ( .__ closure__ Inner) 
    Inner (name) # call directly within 
outer ( "GuiDo")

operation result:

sub method :GuiDo
(<cell at 0x000001D2792EF7C8: function object at 0x000001D2793687B8>,)

eg

2. Return function name

# -*- coding: utf-8 -*-

def sumer(num = 0):
    count = [num]
    def add():
        count[0] += 1
        return count[0]
    return add

f  = sumer(3)
print(f())
print(f())
print(f())

operation result:

4
5
6


Guess you like

Origin blog.51cto.com/3388803/2419968