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