Python high-order functions-closures

Source: Internet
Author: User

Higher-order functions can also return a function as a result value, in addition to the ability to accept functions as parameters.

Here we begin by remembering how the Python code runs when it encounters a function.

After the Python interpreter starts executing, it opens up a space in memory

Whenever a variable is encountered, the corresponding relationship between the variable name and the value is recorded.

But when a function definition is encountered, the interpreter simply reads the function name into memory , indicating that the function exists, and that the variables inside the function and the logic interpreter do not care at all.

When executing to a function call, the Python interpreter will open up a memory to store the contents of the function , at which point the variables in the function are stored in the newly opened memory. The variables in the function can only be used inside the function, and all the contents of this memory will be emptied as the function executes.

Namespaces and Scopes

The namespaces are divided into three types:

Global namespaces

Local namespaces

Built-in namespaces

* The built-in namespace holds the Python interpreter's name for us: Input,print,str,list,tuple ... They are all familiar to us and can be used in a way.

Order of loading and taking values between three namespaces:

Load order: Built-in namespaces (pre-Program load)-Global namespaces (program run: Load from top to bottom) local namespaces (program run: Load only when called)

Value:

Built-in namespaces, local namespaces, and global namespaces, local call spaces

1 x = 12def  F (x):3     print(x)4 5 Print (10)

Global invocation: Built-in namespaces, global namespaces

x = 1def  F (x):    Print(x) F (ten)print(x)

Scope

Scope is the scope of action, according to the effective scope can be divided into global scope and local scope.

Global scope: Contains built-in namespaces, global namespaces , can be referenced anywhere throughout the file, are globally valid

Local scope: Local namespace, only valid locally

The nature of function names

The function name is essentially the memory address of the function.

1. Can be referenced

def func ():     Print ('infunc'= funcprint(f)

2. Elements that can be used as container types

defF1 ():Print('F1')defF2 ():Print('F2')deff3 ():Print('f3') L=[F1,f2,f3]d= {'F1': F1,'F2': F2,'f3': F3}#calledL[0] () d['F2']()

3. Can be used as a function parameter and return value

* Don't you understand? Just remember a word, just use it as a normal variable.

Closed Package

Closure function:

An intrinsic function contains a reference to an outer scope rather than a full-action domain name, which is called a closure function
#函数内部定义的函数称为内部函数

Because of the scope of the relationship, we cannot get the variables and functions inside the function. What if we just want to take it? Come back!

We all know the variables inside the function. If we want to use it outside the function, we can return the variable directly, so what if we want to call the function inside the function outside?

Would it be nice to return the name of the function directly?

This is the most common use of the closure function.

def func ():     ' Eva '    def inner ():         Print (name)     return  = func () f ()
#the __closure__ of the output has a cell element: a closure functiondeffunc (): Name='Eva'    definner ():Print(name)Print(Inner.__closure__)    returnInnerf=func () f ()#the output __closure__ is none: Not a closure functionName ='Egon'defFunc2 ():definner ():Print(name)Print(Inner.__closure__)    returnInnerf2=Func2 () f2 ( )
def wrapper ():     = +    def  func ():        'Eva'        def  Inner ():             Print (Name,money)         return Inner     return  == f () I ()

 from Import Urlopen def index ():     " http://www.xiaohua100.cn/index.html "    def get ():         return urlopen (URL). Read ()     return  == Xiaohua ()print(content)

Namespaces:

A total of three namespaces range from large to small in order: built-in namespaces, global namespaces, local namespaces

Scope (including the scope chain of the function):

A small range can be used in a wide range of
But a large range cannot be used in small areas.
range from large to small (figure)

In a small area, if you want to use a variable that is present in this small range, use your own
If not in a small area, use the upper level, the upper level is not used, and so on.
If none, error

Nesting of functions:

Nested calls

Nested definitions: Functions that are defined internally cannot be called directly at the global

The nature of the function name:

is a variable that holds the memory address where the function resides.

Closures:

An intrinsic function contains a reference to an outer scope rather than a full-action domain name, which is called a closure function

Python high-order functions-closures

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.