How to implement function closure by python
This article mainly introduces the relevant knowledge of python how to achieve function closure, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this python article on how to achieve function closure. Let's take a look at it.
Elements for forming closures
① function nesting
② returns the internal function as a return value
③ internal functions must use variables of external functions
Def make_averager (): # create a list to hold the numeric value nums = [] # create a function Used to calculate the average def averager (n): # add n to the list nums.append (n) # find the average return sum (nums) / len (nums) return averageraverager = make_averager () print (averager (10)) print (averager (20)) print (averager (30))
The outer function returns the inner function to a variable as a return value, and it can always access and modify the variables of the outer function as long as the inner function object is not recycled. Local variables in the outer function are not destroyed.
This is the end of the article on "how to implement function closures in python". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to achieve function closures in python". If you want to learn more, you are welcome to follow the industry information channel.