Python's closure function

Source: Internet
Author: User
Tags closure

An inner function is defined in an outer function, and a temporary variable of the outer function is used in the inner function, and the return value of the outer function is a reference to the inner function. This makes up a closure.

#闭包函数的实例
# outer is a temporary variable where external functions A and B are external functions
def outer (a):
b = 10
# inner is an intrinsic function
def inner ():
#在内函数中 used a temporary variable for the outer function.
Print (A+B)
# The return value of the outer function is a reference to the inner function
return inner

if __name__ = = ' __main__ ':
# Here we call the outer function passed in parameter 5
#此时外函数两个临时变量 A is 5 B is 10, and creates an inner function, and then returns a reference to the inner function to the demo
# when the outer function ends, the inner function will use its own temporary variable, and the temporary variables will not be freed and bound to the inner function.
Demo = outer (5)
# We call an intrinsic function to see if an intrinsic function can use a temporary variable of an external function
# The demo saves the return value of the outer function, which is the reference to the inner function, which is equivalent to executing the inner function
Demo () # 15

Demo2 = outer (7)
Demo2 () #17

Python's closure function

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.