I. Application of function names
A function name is a variable, but it is a special variable that can be executed in conjunction with parentheses.
1. memory address of Function name
1 def func (): 2 Print (" hehe ") 3 Print (func) 4 Results: 5 function func at 0x1101e4e
2. Function names can be assigned to other variables
1 def func (): 2 Print (" hehe ") 3 Print (func) 4 # assign a function to another variable as a variable 5 # function call func ()
3. Function names can be used as elements of a container class
1 deffunc1 ():2 Print("hehe")3 defFunc2 ():4 Print("hehe")5 deffunc3 ():6 Print("hehe")7 defFunc4 ():8 Print("hehe")9LST =[Func1, Func2, func3]Ten forIinchLST: OneI ()
4. Function names can be used as arguments to functions
1 deffunc ():2 Print("did you eat?")3 defFunc2 (FN):4 Print("I'm Func2 .")5FN ()#executes the FN passed over6 Print("I'm Func2 .")7Func2 (func)#The function func is passed as a parameter to the FUNC2 parameter.
5. Function names can be used as return values for functions
1 deffunc_1 ():2 Print("here is the function 1")3 deffunc_2 ():4 Print("here is the function 2")5 Print("here is the function 1")6 returnfunc_27fn = Func_1 ()#Execute function 1. Function 1 Returns the function 2, when FN points to the above function 28FN ()#perform the functions returned above
Two. Closures
What is a closure? A closure is a reference to an inner-layer function, a variable of an outer-layer function (non-global). Called Closures
1 def func1 (): 2 " Alex " 3 def Func2 (): 4 Print # Closed Package 5 Func2 ()6func1 ()7 results:8 Alex
We can use __CLOSURE__ to detect if a function is a closure. Use the name of the letter. __CLOSURE__ returns a cell is a closure. Returning none is not a closure.
1 deffunc1 ():2Name ="Alex"3 defFunc2 ():4 Print(name)#Closed Package5 Func2 ()6 Print(Func2.__closure__)#(<cell at 0x10c2e20a8:str object at7 #0x10c3fc650>,)8Func1 ()
Question, how do I invoke an inner function outside a function?
1 defouter ():2Name ="Alex"3 #intrinsic Functions4 definner ():5 Print(name)6 returnInner7 8fn = outer ()#accessing an external function, obtaining a function address to an intrinsic function9FN ()#Accessing intrinsic functions
What if multiple layers are nested? It's simple, just one layer at a layer, back to the outer layer.
1 def Func1 (): 2 def Func2 (): 3 def func3 (): 4 print ( " hehe " ) 5 return< /span> func3 6 return Func2 7 8 func1 () () ()
By it we can elicit the benefits of closures. Since we have access to internal functions outside of the world, then the time and timing of the internal function access is not necessarily, because externally, I can choose to access the intrinsics at any time. This time, think about, we said before, If a function is executed. The variables in this function and the contents of the local namespace are destroyed. In closures, if the variable is destroyed, the intrinsic function will not execute properly. So, Python rules. If you access the variables in the outer function in the inner function. This variable will not perish. It will be resident in memory, that is. Using closures, you can guarantee that the variables in the outer function are resident in memory. What good is this? Very big benefit. Let's look at a reptile code:
1 fromUrllib.requestImportUrlopen2 defBut ():3Content =urlopen ("http://www.xiaohua100.cn/index.html"). Read ()4 defget_content ():5 returncontent6 returnGet_conte7fn = but ()#It's time to start loading the 100.8 #There is no need to perform very time-consuming network connection operations when you need to use the content in the back.9Content = fn ()#Get contentTen Print(content) OneContent2 = FN ()#Get content back A Print(Content2)
In conclusion, the function of a closure is to allow the variable to reside in memory. For later use of the program
Three. iterators
What is an iterator? Iterator English means iterator.
1L = [1,2,3,4]2L_iter = L.__iter__()#Convert an iterator into an iterator3item = L_iter.__next__()4 Print(item)5item = L_iter.__next__()6 Print(item)7item = L_iter.__next__()8 Print(item)9item = L_iter.__next__()Ten Print(item) Oneitem = L_iter.__next__() A Print(item)
Iterators follow an iterator protocol: you must have the __iter__ method and the __next__ method.
For loop, which can traverse an iterative object, what does his interior actually do?
- Converts an iterative object into an iterator. (The object can be iterated. __iter__ ())
- Internally use the __next__ method, one for each value.
- The exception handling function is added, and the value is automatically stopped after it is taken.
Simulate a for loop with a while loop:
1 l = [1,2,3,4]2 l_iter = L.__iter__()3 while True: 4 try:5 item = l_iter. __next__()6 print(item)7 except stopiteration:8 break
Why do we have a for loop?
Based on the above-mentioned list of this large pile of traversal, smart you immediately see apart from the clues, so you naively loudly shouted, you do not tease me to play it, with the subscript of access, I can traverse a list this way
1 =[1,2,3]23 index=04 while index < len (l): 5 print(L[index])6 index+=178 # To the yarn for loop, to the yarn can iterate, to the yarn iterator
Yes, sequence type strings, lists, tuples have subscripts, you access them in the above way, perfect! But have you ever thought about the feeling of a non-sequential type like a dictionary, a collection, a file object, so, young man, the For loop is based on an iterator protocol that provides a uniform way to traverse all objects, that is, before the traversal, the __iter__ method of the object is called to convert it to an iterator. Then use the iterator protocol to iterate, so that all the objects can be traversed by the For loop, and you see the effect is true, this is the omnipotent for loop, the most important point, into an iterator, in the loop, at the same time in memory only a single piece of data, Significant savings in memory ~
Four. Summary
Iterable: An object that can be iterated. Internal contains __iter__ () function
Iterator: iterator. The internal contains __iter__ () and contains __next__ ().
Features of iterators:
1. Save memory.
2. Inertia mechanism
3. Cannot be repeated, only down execution.
We can think of the content we want to iterate over as bullets. Then, get to the iterator __iter__ () and put the bullets in the magazine. Then the launch is __next__ () to shoot each bullet (element) out. That is, for loop, the first time is __iter__ () To get the iterator. Each subsequent acquisition of the element is done through __next__ (). When the program encounters Stopiteration, it ends the loop.
Application of Python function name, closure, iterator