Problems with closures in Python

Source: Internet
Author: User
Tags closure
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:

  • http://blog.csdn.net/tao01230/article/details/45972763

  • http://python.jobbole.com/82624/

Problems with closures in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.