Python closure details

Source: Internet
Author: User
Closure is actually nothing complicated. In general, if an internal function references a variable in the external scope (but not in the global scope), the internal function is considered as a closure) the word "closure" is believed to be familiar to many students who have programming in mathematics, but sometimes it is difficult to understand it. First look at the definition:

A closure is an entity composed of a function and its associated reference environment. For example, there is a definition in reference resources: when implementing deep constraints, you need to create something that explicitly represents the reference environment and bind it with the relevant subroutine, bind

Is called a closure.

Closure is actually nothing complicated.

In general, if an internal function references a variable in the external scope (but not in the global scope), the internal function is considered as a closure ). It is just an "inner" function, referred to by a name (variable), and this name (variable) is a local variable for the function whose "outer" contains it.

Maybe you still don't understand what a closure is. it doesn't matter. after reading the following small example, you will surely understand it!

#! /Usr/bin/env python
# Coding = UTF-8
# Http://www.pythontab.com

# Define a function
Def plus (number ):

# Define another function in the function. In fact, the function in this function is considered as a closure.
Def plus_in (number_in ):
# Print the number_in variable here, so that you can know which variable is passed in.
Print str (number_in) + "\ r \ n"

Return number + number_in
# Actually, the returned result is the closure result.
Return plus_in


# Assign a value to the plus function. The value 20 indicates the number of the parameter.
V1 = plus (20)

Print v1 (100) # note that 100 actually gives the number_in parameter


Running result:

100

120

Note: 100 is printed by print str (number_in) + "\ r \ n ".

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.