The examples in this article describe the use of Python closures. Share to everyone for your reference, as follows:
Functions can also be defined in Python functions, i.e. closures. In fact, the concept of closure in JS is about the same as in the case of a python closure.
def make_adder (addend): def adder (augend): return augend + addend return adderp = Make_adder (all) Q = Make_ Adder (+) print (P (+)) print (q (100))
The results are: 123 and 144.
Why? In Python all objects, execute P (100), where P is make_adder (23) This object, that is, addend this parameter is 23, you pass in a 100, that is, the Augend parameter is 100, the two add 123 and return.
Did you find make_adder this function, which defines a closure function, but the return returned by Make_adder is the name of the closure function inside, which is the 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 ()
Operation Result:
Tantengdemacbook-pro:learn-python tanteng$ python3 closure.py Hello, ma6174, 1 access! Hello, ma6174, 2 access! Hello, ma6174, 3 access!
The use of closures to implement the function of the counter, which is a feature of closures, the returned value is stored in memory, so you can implement the Count function.
Turn from: Small Talk blog http://www.tantengvip.com/2015/07/python-closure/
I hope this article is helpful for Python program design.