Application of function name (First class object)
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:
def func (): Print (" hehe ") Print (func) # The result is: <function func at 0x00000000029299d8> prints out the Func memory address
2, the function name can be assigned to other variables:
def func (): Print (" hehe ") = Func # assigns a function as a variable to another variable a () # function call func ()
3, the function name can be used as the element of the container class:
deffunc1 ():Print("hehe") defFunc2 ():Print("hehe") deffunc3 ():Print("hehe") LST=[Func1, Func2, func3] forIinchlst:i ()
4, the function name can be used as a function parameter:
deffunc ():Print("did you eat?") defFunc2 (FN):Print("I'm Func2 .") fn ()#executes the FN passed over Print("I'm Func2 .") Func2 (func)#The function name Func is passed as a parameter to the FUNC2 parameter fn
5, the function name can be used as the return value of the function:
deffunc_1 ():Print("here is the function 1") deffunc_2 ():Print("here is the function 2") Print("here is the function 1") returnfunc_2 fn=func_1 ()#Execute function 1, function 1 returns the function 2, when FN points to the above function 2 #The result is: #here is the function 1 #here is the function 1FN ()#perform the function returned above 2 #The result is: #here is the function 2
Second, closed package
What is a closure package? A closure is a reference to an inner layer function (non-global) variable, as shown in the following example:
def func (): = Ten def Inner (): print(a) # closure inner () func () # The result is: Ten
We can use __closure__ to detect whether a function is a closed packet, the name of a functor . __closure__ returns A cell is a closure, and returning none is not a closure.
def func (): = Ten def Inner (): print(a) inner () print(inner. __closure__) # (<cell at 0x00000000025875b8:int object at 0x0000000058e26d40>,) func ()
Question: How do I invoke an inner function outside a function? Specific examples are as follows:
def outer (): ' Hello ' # intrinsic functions def inner (): Print (a) return Inner = Outer () # accesses an external function, gets the memory address of the intrinsic function fn () # access intrinsic function
What if multiple layers of nesting? It's simple, just one layer at a layer to return to the outer layers, the example is as follows:
def Func1 (): def Func2 (): def func3 (): print ( hehe " return func3 return Func2 func1 () () () # Execute func3 with the result: hehe
By it we can draw out the benefits of closures, because we can access the internal functions outside, that time the internal function access time and timing is not necessarily, because outside, I can choose to access the internal function at any time, this time, think, we said before, if a function is finished, The variables in this function and the contents of the local namespace will be destroyed, and in the case of closures, if the variables are destroyed, the intrinsics will not execute properly, sopython stipulates that if you access the variables in the outer function in the inner function, the variable will not perish and will reside in memory , that is, using closures, you can guarantee that the variables in the outer function are resident in memory. What good does it do? There are great benefits, here's a simple code for crawlers:
fromUrllib.requestImportUrlopendefBut (): Content= Urlopen ("http://www.xiaohua100.cn/index.html"). Read ()defget_content ():returncontentreturnget_content fn= but ()#It's time to start loading the 100. #There is no need to perform very time-consuming network connection operations when you need to use the content in the back .Content = fn ()#Get content Print(content) Content2= FN ()#Get content back Print(Content2)
Fully available: The function of a closure is to allow a variable to reside in memory for use by subsequent programs.
Three, iterators
We've been iterating over an iterative object before, so what is an iterative object? First of all, let's look at what we know as an iterative object, and Str,list,tuple,dict,set, so why can we call them an iterative object? Because they all follow an iterative protocol, what is an iterative protocol? First, let's look at the following error code:
#corrects ='ABC' forCinchS:Print(c)#Error forIinch123: Print(i)#Results: #Traceback (most recent): #File "e:/pythondemo/1-basis/test10.py", line 107, in <module> #For i in 123: #TypeError: ' int ' object is not iterable
Pay attention to reading the wrong message There is a sentence:' int ' object is not iterable, translated is an integer type object is non-iterative,iterable represents an iterative, represents an iterative protocol, So how to verify that your data type conforms to the iterative protocol, we can see all the methods defined in the class through the Dir function. Specific examples are as follows:
" my hahaha. " Print (dir (s)) # you can print methods and functions in an object Print (dir (str)) # You can also print methods and functions declared in a class
In the print results, looking for __iter__, if you can find, then the object of this class is an iterative object. We found that __iter__ can be found in the string , continue to look at list,tuple,dict,set, as follows:
Print (dir (list)) Print (dir (tuple)) Print (dir (dict)) Print (dir (set)) Print (Dir (Open ("test9.py"))) # File Object
We've found that there are __iter__ functions available for the For loop, including range, and you can try it yourself.
In conclusion, by looking for __iter__ to see if an object is an iterative object, we can also see what type of an object it is by using the isinstence () function, as shown in the following example:
ls = [a] Ls_iter= ls.__iter__()#get a list of LS iterators fromCollectionsImportiterable fromCollectionsImportIteratorPrint(Isinstance (ls,iterable))#True ls is an instance of an iterative object Print(Isinstance (Ls,iterator))#False ls is not an instance of an iterator Print(Isinstance (ls_iter,iterable))#True Ls_iter is an instance of an iterative object Print(Isinstance (Ls_iter,iterator))#True Ls_iter is an instance of an iterator
In conclusion, we can determine that if the object has a __iter__ function, then we think that this object adheres to the iterative protocol, we can get to the corresponding iterator, the above code is __iter__ to help us get to the object iterator, we use the iterator in the _ _next__ () to get an element in an iterator, what is the work of the For loop we talked about earlier? Keep looking at the following code:
s ="I love Beijing Tian ' an gate"C= S.__iter__()#Get iterators Print(c.__next__())#iterate with an iterator to get an element: I Print(c.__next__())#Love Print(c.__next__())#North Print(c.__next__())#Beijing Print(c.__next__())#days Print(c.__next__())#Ann Print(c.__next__())#Door Print(c.__next__())#stopiteration
The For loop is as follows:
for inch [[+] : Print (i)
Use the while loop + iterator below to simulate a for loop (which must be mastered):
LST = [+= ]= lst. __iter__() while 1: try: = Lst_iter . __next__() print(i) except stopiteration: Break
Summarize:
Iterable: An iterative object that contains the __iter__ () function and does not contain the __next__ () function;
Iterator: An iterator that contains the __iter__ () function internally and contains the __next__ () function;
Iterator Features:
1, save memory (introduced in the next generator);
2, inertia mechanism (encountered __next__ only take one);
3, can not be repeated, can only be executed downward;
We can take the content that we want to iterate as a bullet, then, get to the iterator __iter__ (), put the bullets in the magazine, and then launch is __next__ () each bullet (element) out, that is, for the loop, the start is __iter__ () To get the iterator, each subsequent fetch element is done through __next__ (), and when the program encounters stopiteration it ends the loop.
Python's function name, closure, iterator