Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle of function nesting, function as variable and closure in python?

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what is the principle of function nesting, function as variable and closure in python". In daily operation, it is believed that many people have doubts about function nesting, function as variable and the principle of closure in python. The editor consulted all kinds of data and sorted out simple and useful operation methods. I hope it will be helpful for you to answer the questions of "function nesting, function as variable and closure principle in python". Next, please follow the editor to study!

Nested functions:

Python allows you to create nested functions. In other words, we can define a function in a function, and the existing scope and variable lifetime remain the same.

Example:

# encoding=utf-8def outer (): name= "python" def inner (): # function defined inside the outer function print name return inner () # returns the internal function outer ()

Results:

Understand:

In the inner function, the python parser needs to find a local variable called name. After the search fails, it will continue to look in the upper scope. This upper scope is defined in the outer function, and the python function can access the closed scope.

For the last sentence in the outer function, returning the result of the inner function call, it is very important to know that inner is only a variable name that follows the python variable resolution rules, and the python interpreter will first look for matching variables in the scope of outer in the face of the variable name inner.

Return the variable inner that happens to be the function identifier as the return value, and every time the function outer is called, the function inner will be redefined, and if it is not returned as a variable, it will no longer exist after each execution.

In python, a function is an object, and it is just some ordinary value. That is to say, you can pass functions to other functions like arguments or return functions from them.

The inner function of return returns only the address of the function without parentheses:

Code:

# encoding=utf-8def outer (): name= "python" def inner (): # function return name return inner# defined inside the outer function returns the internal function print outer ()

Results:

When the outer function outer () is executed, the function reference (function name) of the inner function-inner is returned. If you want to execute the inner function, you need to add a parenthesis after outer (), that is, outer () (), to let the inner function execute.

Code:

# encoding=utf-8def outer (): name= "python" def inner (): # function return name return inner# defined inside the outer function returns the internal function print outer ()

Results:

Function as a variable:

Example:

# encoding=utf-8def add (XMague y): return x+ydef sub (XMagne y): return x-ydef apply (func,x,y): return func (XMagol y) print "apply (add,2,1):", apply (add,2,1) print "apply (sub,2,1):", apply (sub,2,1)

Results:

The apply function is ready to receive a variable of a function, which is just an ordinary variable, just like any other variable. Then we call the function passed in: "() represents the called operation and the value contained in the calling variable."

Outside the function, we can also see that the transfer function has no special syntax, and the name of the function is just the same table identifier as other variables.

The understanding of closures:

Let's look at an example first.

# encoding=utf-8def outer (): name= "python" def inner (): what external variables are included in the print name return innerres=outer () res () print res.func_closure# print closure

Results:

In this example, inner is returned by outer as a function, saved in the variable res, and can also be called res (). Why can it be called?

From the scope and lifetime of the above variable, it is not difficult to understand that name is a local variable in the function outer, that is, the variable exists only when outer is running.

According to the mode of operation of python, we cannot continue to call the inner function after the function outer exits, and the variable name no longer exists when the inner function is called, but why did we call it successfully?

Which brings us back to the issue of closures, python supports a feature called function closures.

What is a closure?

If a function is defined within the scope of another function and references the variables of the outer function, the function is called a closure. Closure is a feature supported by Python, which allows functions defined in non-global scope to refer to variables in their peripheral space, which are called environment variables of this function. The environment variable and this non-global function form the closure.

The inner () function in the above example is a closure, which itself is a function, and it can also access variables other than itself. This can be concluded by looking at the func_closure property of the function, which contains the values in the closed scope (only the captured values, such as name, will be included. If other values are defined in the outer, there will be no values in the closed scope)

Every time the function outer is called, the inner function is redefined, and the inner result returned above is the same each time, because the name has not changed.

As shown in the following example, if we change the function a little bit, the result will be different.

Code:

# encoding=utf-8def outer (name): def inner (): print name return innerres1=outer ("python") # return closure res2=outer ("java") # return closure res1 () # execute function res2 ()

Results:

Analysis:

In the previous example,

Def outer (): name= "python" def inner (): print name return inner

After the outer function is run, it returns a function + the variables needed by the function.

Name = "python" def inner (): print name

The above three lines are the contents returned as a whole.

If you add an external integer variable to the outer function, refer to it in the inner function:

# encoding=utf-8def outer (): name= "python" nbr=12 def inner (): print name print nbr return inner# returns a function object without parentheses, not a function call res=outer () res () # call the inner function print res.func_closure# to print what external variables are contained in the closure

Results:

D:\ > python test.pypython12 (,)

Where res = outer () assigns the inner function object to res, because there are no parentheses, so instead of calling but returning a function object

Res () calls the inner function

Print res.func_closure is to print which external variables are contained in the closure. You can see that there are two in the result: python and 12.

()

Closure features:

The function object returned by a function, which, if executed, depends on the value of a variable that is not inside the function. At this time, the actual content returned by the function is as follows:

1 function object

2 external variables and variable values that the function object needs to use

That's the closure.

A closure must be nested in a function and must return a function object that calls an external variable.

In the above example, compared to inner, the outer function is its global variable, just as if you write a function that uses the global variable defined by the environment outside the function, it is a relative concept.

The popular understanding is that the execution of the inner function requires the use of a variable of the outer function, so the two things that combine the outer variable with the inner function are closures.

At this point, the study of "what is the principle of function nesting, function as a variable and closure in python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report