Python closures and python closures

Source: Internet
Author: User

Python closures and python closures

 1 def print_msg(msg): 2 # This is the outer enclosing function 3  4     def printer(): 5 # This is the nested function 6         print(msg) 7  8     printer() 9 10 # We execute the function11 # Output: Hello12 print_msg("Hello")

As shown above, printer is an embedded function. According to the legb e Principle, the incoming msg parameter is obtained.

def print_msg(msg):# This is the outer enclosing function    def printer():# This is the nested function        print(msg)    return printer  # this got changed# Now let's try calling this function.# Output: Helloanother = print_msg("Hello")another()

If you replace the printer call in print_msg with the return value and assign the value to the variable another, print another will get: <function printer at 0x02666AB0>, it can be seen that the value assigned to another is the value of print_msg after execution, that is, printer. Then another () represents the execution of printer (). At this time, printer () can still remember the value of msg, even if the print_msg function has been executed, or you delete print_msg after another = print_msg ("hello"), del print_msg is fine.

 

The closure must contain:

  • We must have a nested function (function inside a function). a nested function
  • The nested function must refer to a value defined in the enclosing function. nested functions must reference an externally defined variable.
  • The enclosing function must return the nested function. The enclosing function returns a nested function.

_ Closure __

The closure attribute returns a cell-containing tuples in which each cell stores the scope variable.

Print another. _ closure __

>>> (<Cell at 0x024FC990: str object at 0x024FC960> ,)

Print another. _ closure _ [0]. cell_contents

>>> Hello

Reference: https://www.programiz.com/python-programming/closure

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.