In Python, Why can a function return a function defined inside a function? Reply content:
The subject may not understand
"In Python, functions are also objects"
This essence. Let's take a look at this question from the very basic concept:
1. Everything in Python is an object
This is probably the most useful sentence for learning Python. You must already know the built-in data structures such as list, tuple, and dict in Python. When you execute:
alist = [1, 2, 3]
The typical problem encountered by the subject is that it regards the modifier as a package and considers that addspam is called before useful is called. In fact, useful is not packaged by addspam,Replace. New is called to call useful. The remaining fn points to the original useful, which requires knowledge points such as the first type of function and scope inheritance. Variable Parameter * args is another knowledge point of interference. Replace it with x and y. @ In Python is just a syntax sugar. When you declare useful, interpreter checks that you have an external modifier @ addspam, at this time, you can roughly understand that the interpreter has done the following:
useful = addspam(useful)
Very good question!
Please search higher order functions for more information.
Because I have no ability to explain it clearly, I will write a few blog articles that I saw when learning functional programming to help you understand.
Function programming | cool shell
Function programming of Python Modifier
1.6 Higher-Order Functions
6. Functional Programming
I like the last article to better understand the effect through examples. In Python, functions are nothing special, but an object. You do not understand the modifier.
After modifying useful with addspam, you should understand that this function has become new.
When the useful function is called, the new function is actually called. Without replication, a function is also an object. It is basically the same as returning a list and a dict.
Try to create a function in Python REPL:
>>> Def foobar (): print ("hello") >>>> foobar >>> func_list = [foobar, foobar, foobar] >>>> func_list [0] ()
It is not a simple function. At least in Python, def-defined functions and lambda-defined functions include closure.
What is closure? This is not a single sentence. I don't think I can say yes, so I should search for it myself.
Don't say I discriminate against Baidu for this problem. How nice is it to search for nested functions on Google.