This is a creation in Article, where the information may have evolved or changed.
The role of closures
In a word, the effect of closures: The method is stored in a variable.
As for the reason or purpose of the closure, or why the method is stored in a variable, it will be said later.
Conditions for closures
To avoid describing a concept in a large paragraph, we rationally divide the conditions of closures into 3:
- An intrinsic function is defined in the outer function
- The inner function uses a variable of the outer function
- The outer function returns a reference to the inner function, or, the inner function is called directly in the outer function
P.S.
- The outer and inner functions are the outer functions and intrinsic functions in the nested functions.
- It is also because of the need to nest functions that the language of the unsupported nested functions naturally does not support such closures
- Condition 3 is divided into two categories, more cases are the former, and the latter (the outer function calls the inner function directly) the use of more is to ensure that the code is concise, and so keep concise does not necessarily use closures.
Examples of closures
"Talk is cheap, show me your code."
I have always felt that in programming, too much human language can produce too many ambiguities, and may even cause the audience to be unable to understand the concept because the things they say are too abstract.
The best way to solve this problem is to look at the code, one of the advantages of programming language compared to human language is that it greatly reduces the ambiguity of language. At the same time, through multiple code instances, the human brain naturally extracts the common denominator in multiple instances to understand the abstract concept.
In conjunction with the three conditions of closures, let's look at the closure example:
def outer(b): def inner(a): # 条件1 print(a + b) # 条件2 return inner # 条件3 # 调用o = outer(1)o(2)
Python's code is pretty straightforward.
In general, after the function ends, the variables in the function should be destroyed, but this closure is a special case--o and O2 in 1 and 20 are preserved.
O and O2 seem to have a sense of familiarity, they are like two objects-both "objects" are from the same "class", and two "object instances" of the difference is that there is a addend, respectively, 1 and 20 (of course, the two variables have different reference addresses).
Now, let's change the third condition in the code example, and soon the "outer function returns a reference to an inner function called an inner function" in an outer function ":
def outer(a, b): def inner(a): # 条件1 print(a + b) # 条件2 inner(b) # 条件3 # 调用o = outer(100,1)
At this point, the entire closure function is called like a normal function, passing in two parameters, the print also as expected.
It can only be said that the logic in the outer function is too complex, the inner can be complex code "modular", and then call, can increase the simplicity of. In this case, the inner function is generally called only once, and is only called here, and is also good to manage some of it here.
Next, we'll look at other languages like closures:
func outer(i int) func() int { return func() int { // 条件1(匿名)+ 条件3 i++ // 条件2 return i }}// 调用o := outer(1)o()
This golang example of the closure and Python example of the larger distance is also the inside of the function is replaced by anonymous, it seems to be more cool. And the following PHP is almost the same as Python.
function outer($str1) { $outerStr = $str1; $inner = function($str2) { // 条件1 echo $str2 . $outerStr; // 条件2 }; return $inner; // 条件3}// 调用$o = outer("hahaha");$o("emmm");
Reasons for closures
After looking at the example above, the novice should have a certain understanding of the concept of closures, and even a bit of an idea.
Back to the very beginning of the problem, the reason for closures.
If you say, "Save a method to a variable" is the purpose of the closure, then the next question is obvious: why do you want to store the method in a variable? Is it bad to call a method (function) directly?
Closures save state information for a function
Let's start with an example:
def outer(b): def inner(a): print(a + b) return inner o = outer(1)o(2) # 3o(100) # 101o2 = outer(20)o2(100) # 120
o This variable corresponds to the closure of this b=1 information, and then whether it is called o(2) or o(100) , b=1 this information will still exist and participate in the operation with subsequent parameters. In the same vein, the closure of the O2 variable corresponds to b=20 this information.
Since the function is exited, the function is not destroyed and the information of the closure is not destroyed, so the information can be used later.
Grammar sugar
For the simplicity and ease of understanding of code, we often use or even create some grammatical sugars.
And in Python, there's a pretty good example of an adorner, an example that's already been used, and a tangent-oriented login implementation:
# 先实现一个类似于装饰器的函数def decorator(func): def inner(): print 'before function' func() # function print 'after function' return inner# 实现一个假装在登录的登录函数def login(): print 'login function complete.'# 将登录函数“套上”装饰器login = decorator(login) login()
The whole process is similar to AOP, and scenes are often used, such as the running of statistical functions, log-in, unified filtering, and so on.
What's more, using closures to create syntactic sugars in specific scenarios to simplify the code, refer to this example, which can be used instead of switch (but the simple addition and subtraction operations here are mentally retarded, with a certain degree of complexity that can appear to be advantageous):
def operator(o): def plus(x, y): print(x + y) def minus(x, y): print(x - y) if o == '+': return plus if o == '-': return minusdef f(x, o, y): operator(o)(x, y)
Function-Type programming
The famous lambda, this can refer to this link.
Summarize
Closures can store methods in variables and implement some wonderful things.
It's like a flavoring, not essential, but it's the icing on the cake.
Let's do this.
If there is any mistake, please point out that more attention is paid to the fried fish.