Python Learning 13th Day iterator Builder

Source: Internet
Author: User
Tags closure generator generator generator iterable wrapper

1. Summary of function Review

#function--2 days    #definition and invocation of functions    #def function name (formal parameter):        #function Body        #return value    #Call Function name (argument)    #standing at the angle of the parameter: positional parameters, *args, default parameters (traps), **kwargs    #stand at the angle of the argument: according to the location of the transmission, according to the key word    #return value: No return value returns a value that returns multiple values    #receive return value: No return value is not received, return a value received with a variable, return multiple values with a variable or a corresponding number of variables received#closure Function--a variable that references an external function in an intrinsic function#Adorner Function--the adorner must be a closure function    #The role of adorners: Add new functions before and after this function without changing the way the original function is called    #perfectly conforms to a development principle: the open and closed principle        #is developed for the extension        #The modification is closed.    #the base decorator        #From functools Import wraps        #def Wrapper (func):        #@wraps (func)        #def Inner (*args,**kwargs):        #"' the code added before the function is called '        #ret = func (*args,**kwargs) # Func is a decorated function called here        #"' code added after a function is called '        #return ret        #return inner        #Use--@wrapper        #@wrapper        #def func (): #inner        #Pass        #        #func.__name__    #Adorner with Parameters        #@wrapper--> @warapper (argument)        #three-layer nested functions        #def outer (formal parameters):        #def Wrapper (func):        #def Inner (*args,**kwargs):        #"' the code added before the function is called '        #ret = func (*args,**kwargs) # Func is a decorated function called here        #"' code added after a function is called '        #return ret        #return inner        #return wrapper        #@outer (True)        #def func ():        #Pass    #multiple adorners decorate a function        #Russian set of dolls    #def wrapper1 (func):        #@wraps (func)        #def Inner (*args,**kwargs):        #print (' before 1 ')        #print (' ****** ')        #ret = func (*args,**kwargs) # Func is a decorated function called here        #"' code added after a function is called '        #return ret    #def wrapper2 (func):    #@wraps (func)    #def Inner (*args,**kwargs):    #print (' before 2 ')    #ret = func (*args,**kwargs) # Func is a decorated function called here    #"' code added after a function is called '    #return ret    #@wrapper1    #@wrapper2    #def func ():    #print (' 111 ')#iterators and generators--two days#built-in functions--two days
View Code

2. Iterative and iterative protocols are available

What if I now have a list of l=[' A ', ' B ', ' C ', ' d ', ' e ', and I want to fetch the contents of the list in several ways?

First, I can index the value of l[0], and then we can also use for the loop to take the value ah?

Have you ever thought about it, there is a subtle difference between using the index value and the for loop to take the value.

If you use an index to take a value, you can take the value anywhere, if you want to know where the value is.

If we use a for loop to get the value, we take each value, do not need to care about the location of each value, because only the order of the value, and can not skip any one directly to fetch the value of another location.

But have you ever wondered why we can use a for loop to take a value?

How does the For loop work inside?

To understand what's going on for the for Loop, let's start from the code point of view.

First, we make a for loop for a list.

For i in [1,2,3,4]:      print (i)

There's no problem with the code above, but let's change the case to loop a number 1234 try

For i in 1234    print (i) Results: Traceback (most recent call last):  File "test.py", line 4, in <module> for    i I n 1234:typeerror: ' int ' object is not iterable

Look, an error has been made! What's wrong with the report? "TypeError: ' int ' object is not iterable", say int type not a iterable, what is this iterable?

If you do not know what is iterable, we can turn over the dictionary, first of all to get a Chinese explanation, although the translation came over you may not know, but it's okay, I will take you step-by-step analysis.

Iterative and iterative protocols what is called iteration now, we've got a new clue, there's a call The concept of "iterative"

First, we analyze from an error, as if the reason why 1234 is not for the loop, because it is not iterative. Then if "iterative", it should be able to be a for loop.

We know that strings, lists, tuples, dictionaries , and collections can all be used for loops, indicating that they are all iterative .

How can we prove it?

From collections import iterable                             L = [1,2,3,4]                t = (1,2,3,4)                d = {1:2,3:4}                s = {1,2,3,4}                                             print (isinst Ance (l,iterable)) print (Isinstance (t,iterable)) print (Isinstance (d,iterable)) print (Isinstance (s,iterable))

In combination with the phenomenon of using the For loop to take a value, and then literally, the iteration is what we just said, that the data in a dataset can be taken out "one next to another," called an iteration .

An iterative protocol

a requirement that can be iterated over is called an iterative protocol. the definition of an iterative protocol is very simple, which is to implement the __iter__ method internally.

3. iterators

the concept of iterators#iterator Protocol--an iterator that internally contains __next__ and __iter__ methods#iterator protocol and iterative protocol#can be iterated by the For Loop#There are __iter__ methods in an iterative interior#as long as the iterator is bound to iterate#an iterator can be obtained by iterating over the. __iter__ () method.#The __next__ () method in the iterator can get the value one by one#The For loop is actually using iterators#iterator#can iterate over objects#just give you the memory address .#print ([].__iter__ ())#print (range)# for#It is only possible to iterate over objects to use the for#when we come across a new variable, unsure if it can be used for a loop, we'll tell if it's iterative.#For i in L:#Pass#iterator = l.__iter__ ()#iterator.__next__ ()#Benefits of Iterators:    #a value from one of the container types will fetch all the values.     #Saves memory space        #iterators do not occupy a large chunk of memory in memory,            #instead, each time the loop generates a            #every time next time you give me a#Range#F#L = [1,2,3,45]#iterator = l.__iter__ ()#While True:#print (iterator.__next__ ())#Print (range (100000000000000))#Print (range (3))#Print (List (range (3)))#def func ():#For i in range (2000000):#i = ' wahaha%s '%i#return I#Generator-Iterator#Generator Functions--essentially, we write our own functions.#Builder ExpressionL = [1,2,3,4,5] forIinchL:Print(i)ifi = = 2:         Break forIinchL:Print(i)
View Code

4. Generator

There are two types of iterators we know: One is to return the method directly, and one is to have an iterative object obtained by executing the ITER method, which has the advantage of saving memory.

If in some cases, we also need to save memory, we can only write ourselves. What we write ourselves is called the generator, which implements the function of the iterator.

The generators available in Python:

1. Generator function: General function definition, however, returns the result using the yield statement instead of the return statement. The yield statement returns one result at a time, in the middle of each result, suspends the state of the function so that the next time it leaves, it resumes execution.

2. Generator expression: Similar to list derivation, however, the generator returns an object that produces results on demand, rather than building a list of results at a time

Generator generator:

Essence: iterators (so we have the __iter__ method and the __next__ method, we do not need to implement)

Features: Lazy operation, developer customization

Code

Python Learning 13th Day iterator Builder

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.