Closed Package
A function is an object, so it can be returned as a result of a function.
When a function is combined with its environment variables, it forms a closure (closure). In Python, the so-called closure is a function object that contains the value of an environment variable. The environment variable value is saved in the __closure__ property of the Function object
Considerations for using closures 1. In closures, you cannot modify the local variables of the outer scope.
Role
- Purpose 1: When the closure has been executed, the current operating environment can still be maintained.
For example, if you want the result of each execution of the function, it is based on the last running result of the function. I illustrate this with an example of a board game like this. Assuming the checkerboard size is 50*50 and the upper-left corner is the coordinate system origin (0,0), I need a function that receives 2 parameters, namely direction (direction), step (step), which controls the movement of the pieces. The new coordinates of the chess piece movement are in addition to the direction and the step length, of course, according to the original coordinate point, the closure can be used to maintain the original position of the piece of the coordinates.
- Purpose 2: Closures can get different results based on local variables of the outer scope
This is a bit like the function of a similar configuration, we can modify the external variables, closures according to this variable to show a different function. For example, sometimes we need to divide the special lines of certain files
In functional programming with Python, closures persist on data and produce different functions according to configuration.
Reference Links:
Problems with closures in Python