Example of how to use a function (closure) in a Python function.
This example describes how to use the Python closure. We will share this with you for your reference. The details are as follows:
You can also define functions, that is, closures, in Python functions. Similar to the closure concept in js, here is an example of closure in Python.
def make_adder(addend): def adder(augend): return augend + addend return adderp = make_adder(23)q = make_adder(44)print(p(100))print(q(100))
Running result: 123 and 144.
Why? In Python, everything is an object. Execute p (100), where p is the make_adder (23) object, that is, the addend parameter is 23, and you pass in another 100, that is, the augend parameter is 100, and the sum of the two is 123, and return.
Have you found that the make_adder function defines a closure function, but the return returned by make_adder is the name of the closure function, which is a feature of the closure function.
Let's look at a Python closure example:
def hellocounter (name): count=[0] def counter(): count[0]+=1 print('Hello,',name,',',count[0],' access!') return counterhello = hellocounter('ma6174')hello()hello()hello()
Running result:
tantengdeMacBook-Pro:learn-python tanteng$ python3 closure.py Hello, ma6174 , 1 access!Hello, ma6174 , 2 access!Hello, ma6174 , 3 access!
The counter function is implemented using the closure, which is also a feature of the closure. The returned values are stored in the memory, so the counting function can be implemented.