Python Closure details

Source: Internet
Author: User
The word "closure" believes that most students who have studied programming are not unfamiliar, but sometimes it is difficult to understand them. First look at the definition:

Closures are entities that are composed of functions and their associated reference environment. For example, there is a definition in the reference resource: When implementing a deep constraint, you need to create something that can explicitly represent the reference environment and bundle it with the associated subroutine so that it binds

The whole is called closures.

Python closures (closure) are not really a complex thing.

In layman's parlance, if a reference is made to a variable in an external scope (but not at the global scope), then the intrinsic function is considered a closure (closure). It is simply an "inner" function, which is referred to by a name (variable), and the name (variable) is a local variable for the function that the outer layer contains.

See here maybe you still don't understand what is closure, it's okay, read the following small example you will understand!

#! /usr/bin/env python
# Coding=utf-8
# http://www.pythontab.com

#定义一个函数
Def plus (number):

#在函数内部再定义一个函数, in fact, the function inside is considered a closure.
def plus_in (number_in):
#这里打印一下number_in变量 so that you can get a clearer idea of which variable to pass in
Print str (number_in) + "\ r \ n"

Return number+number_in
#其实这里返回的就是闭包的结果
Return plus_in


#给plus函数赋值, this 20 is the parameter number.
V1=plus (20)

Print V1 (#注意这里的100其实给参数number_in)


Operation Result:

100

120

Note: 100 is print str (number_in) + "\ r \ n" Printed results OH
  • 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.