Step by step teach you to know Python closures (reprint)

What is closure? Closures what's the use? Why closures? Today we took these three problems step by step understanding closures. Closures and function closely linked, it is necessary to introduce before the closure start with some background information, such as the concept of nested functions, variable scope, etc.

Scope

Scope range runtime variables can be accessed, in the definition of the variables is a function of local variables, local variables scope only within the internal range of the function, it can not be referenced outside the function.

DEF foo ():
     NUM = 10 # the local variable Print ( NUM ) # NameError: name 'NUM' IS Not defined

Variable is defined in the outermost module is a global variable, it is visible in the global scope, of course, a function which can be read to the global variable. E.g:

NUM = 10 # global variable DEF foo (): Print ( NUM ) # 10

Nested functions

Functions can be defined not only in the outermost layer of the module, can also be defined within another function, such as referred to in the definition of the function inside the function nested function (nested function), for example:

DEF print_msg ():
     # print_msg enclosing function is MSG = "Zen of Python" DEF Printer (): # nested functions Printer Print ( MSG ) Printer () # output of Python Zen print_msg ()

For the nested function, it can access to the outer scope of its declaration nonlocal (non-local) variables, variables such as sample code msgcan be nested function printernormally accessible.

Is there a possibility even if the function itself out of the scope of local variables can also be accessed to get it? The answer is Closures

What is Closures

As a function of first-class objects, it can be returned as the return value of the function, we now consider the following example:

DEF print_msg ():
     # print_msg enclosing function is MSG = "Zen of Python" DEF Printer (): # nested functions Printer Print ( MSG ) return Printer Another = print_msg () # output of Python Zen Another ()

This code and the previous example results exactly the same, the same output "zen of python". The difference is that the internal function printerdirectly returned as the return value.

Under normal circumstances, the function of local variables are only available during the execution of the function, once print_msg()after the execution, we think that msgthe variable is no longer available. However, here we find after print_msg executed, when calling another value of the variable msg normal output, and this is the role of closures, the closure makes it possible to access a local variable is outside the function.

After reading this example, let's define the closure, is explained on Wikipedia:

In computer science, closures (Closure) is a lexical closures (Lexical Closure) for short, is a reference to the function of free variables. This free variables referenced and this function will exist together, even if it has left the creation of an environment is no exception. Therefore, there is another way of saying that the closure is a combination of entities and functions associated therewith environment references made.

Here anotheris a closure, the closure is essentially a function, which has two parts, printerfunctions, and variables msg. Closures such values of these variables are always stored in memory.

Closures, by definition, a closed package, wrapped inside a free variable, like property values ​​defined in the class inside the visible range of free variables along with the package, where you can access to this package, where you can access to this free variable.

Why use closures

Closure avoids the use of global variables, in addition, closure and allows some of the data it operates on function (environment) connected together. This object-oriented programming is very similar, the surface of the object programming, objects allow us to some data (properties of the object) with one or more associated methods.

In general, when the object is only one way, then the use of closures is the better choice. Look at an example:

def adder(x):
    def wrapper(y): return x + y return wrapper adder5 = adder(5) # 输出 15 adder5(10) # 输出 11 adder5(6) 

This is achieved with a more elegant than the class, in addition to the decorator is based on a scenario closure.

All functions have a __closure__property, if the function is a closure, then it returns a tuple of objects of cell objects. cell_contents target cell property is the closure free variables.

>>> adder.__closure__
>>> adder5.__closure__ (<cell at 0x103075910: int object at 0x7fd251604518>,) >>> adder5.__closure__[0].cell_contents 5 

This explains why, after departing from the local variables function, may also be accessed outside the function as it is stored in the closure in the cell_contents.

 

 

Reprinted address: https: //foofish.net/python-closure.html

Guess you like

Origin www.cnblogs.com/sidianok/p/11946671.html