I have created a function that returns another function. And the inner function is known as a closure. A “closure” is an expression (typically a function) that can have free variables together with an environment that binds those variables (that “closes” the expression). With closures, we can do other neat things like this:
The inner function now becomes something like a method in OOP. It controls the way the variable y is accessed from the outside.
Problem and HowTo
But there’s a problem when we want to do this in Python 2.7. The above code works only in Python 3.x. The nonlocal keyword does not exist in Python 2.7. To solve this problem, we can use dictionaries (or we can also create another object) to store the y variable in a namespace that the inner function can access.
* [Python 學習筆記] 函式、類別與模組 : 函式 (lambda 運算式)