Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement function closure by python

Shulou Source: shulou.com Published: 2022-05-31 10:46:41 09月29日 Update

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.

Tags: Functions closures variables knowledge content inner layer outer layer average article value object local simple operation numerical value article easy to understand more see industry elements Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Information Huawei Shulou Tech Info Shulou Technology