How to use the closure of Python
This article introduces the relevant knowledge of "how to use Python closures". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Definition and use of closures
When the returned internal function uses the variables of the external function, the closure is formed.
Closures can save variables of external functions and improve the reusability of code.
The standard format for implementing closures:
1. Function nesting
two。 Internal functions use variables or parameters of external functions
3. The external function returns the internal function
When the returned internal function uses the variables of the external function, it forms a closure that can save the variables of the external function, and can also improve the reusability of the code to achieve the standard format of the closure: 1. Function nesting 2. The internal function uses the variable or parameter 3 of the external function. External function returns inner function''# Definitions a closure def outer (): # external function print 1 def inner (): # Internal function print (n) # external function returns a reference to the inner function (without parentheses ha) return inner outer () # the outer function does not execute the inner function # inner () # cannot call the inner function directly The function ret=outer () # refers the inner function to retprint (ret) ret () # the use of def person (name): def say (msg): print (f'{name} say: {msg}') return say tom=person ('Tom') rose=person (' Rose') tom ('Hello') rose (' World') 2. The function within the closure modifies the variable defined by the outer function (plus nonlocal) def outer (): Number1 def inner (): nonlocal n # will report an error without adding n=n+10 print (n) print (n) # output 1 return inner fun=outer () fun () # output 11fun () # output 21 "how to use the closure of Python" Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!