Python full stack development five iterator builder decorator

Source: Internet
Author: User

One, iterator

An iterator is an object that remembers where to traverse. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.

Iterators have two basic methods:iter () and next ().

A string, list, or tuple object can be used to create an iterator, and the method of generating the iterator is ITER ():

>>li = [1,2,3,4,5]>>it = iter (LI)#generate an iterator>>it.__next__()1>>next (IT)#both of these next can be used2>> forIinchit:Print(i)345#when the iteration is complete, the data inside the iterator is gone.>>type (IT)<class 'List_iterator'>#type is an iterator type
Second, generator

Before we describe the generator, let's start by understanding the list generation:

#a list of common definitions to write the list to death directlyLi = [1,2,3,4,5]#using list generation, you can add some new properties to the listLi1= [A*a forAinchRange (10)]Print(LI1)#You can also use the following two methods ofLi2= List (Map (LambdaX:x+1, Li))Print(Li2) a= [] forIinchRange (10): A.append (i+1)Print(a)#as you can see from the above comparison, the second method code is the simplest, that is, the list-generating

Although there are list generation, you can simplify the operation of generating a specific list, but when the list data is too large, it consumes too much memory, and the list is not always used, and there is one side loop in Python that calculates the mechanism of the generator.

The first form of representation of the generator:

#Create a generatorLi= (a*a forAinchRange (10))Print(LI)#<generator object <genexpr> at 0x00000000027bd468>, returns a generator object, using next to invoke the objectPrint(Li.__next__())Print(Next (LI))#and can only be called once and cannot be called back" "As we've said, generator saves the algorithm, and each time we call next (g), it calculates the value of the next element of G, until the last element is calculated, and when there are no more elements, the Stopiteration error is thrown. In general, we use a for loop to call all the data" " forIinchLi:Print(i)

The second form of representation of the generator:

Generator: A function call returns an iterator, which is called the Generator (generator), if the function contains the yield syntax, then this function will become the generator and the normal function is different, the generator is a return iterator function, can only be used for iterative operations, A simpler understanding of the generator is an iterator. Invokes a generator function that returns an Iterator object.

Yield syntax: Whenever the line count runs to yield it interrupts and saves all current running information, and continues to run from where it was interrupted after the next () method is executed.

#generate a Fibonacci sequencedeffib (max): A,b,n= 0,0,1 whileN <Max:a, b= b,a+B N+=1return ' Done'C= FIB (5)Print(c)#disadvantages, will be directly all generated#turn the function into a generatordeffib2 (max): A,b,n= 0,0,1 whileN <Max:yieldB#Once once , once again, run the following code and activate it with nextA, B = b,a+B N+=1D= FIB2 (5)Print(Next (d))

The following is a single-threaded concurrency effect using yield, which can also be understood as a co-process (which is said later):

Import TimedefConsumer (name):Print('%s ready to eat buns!'%name) whileTrue:baozi=yield               #saves the value of the current state and exits the function        Print('Bun [%s] came, eaten by [%s]! '%(baozi,name))#C = Consumer (' Alix ') generates a generator object#c.__next__ () Call builderdefproducer (): C= Consumer ('a') C2= Consumer ('b') c.__next__() c2.__next__()    Print('I'm getting ready to make buns.')     forIinchRange (10): Time.sleep (1)        Print('made 1 buns in two halves .') c.send (i)#give yield a value and wake yieldC2.send (i) producer ()
Three, the decoration device
Adorner: Essentially a function that adds additional functionality to other functions
Principle: 1, cannot modify the source code of the decorated function
2. Cannot modify the calling mode of the modified function

In front of the adorner we do some knowledge of the adorner reserve:

1. function is ' variable '
2. Higher-order functions
1. Pass a function name as an argument to another function (add the source code that does not modify the function)
2. The return value contains the function name (does not modify the function's Calling method)
3. Nesting functions

A function is a "variable":

A function is defined so that it is stored in memory like a variable, which makes sense when we go to invoke it.

#function is variable#def foo ():#print (' In the Foo ')#foo ()#that is, there is no need to consider the order of definition of functions, just like defining variablesdefBar ():Print('In the bar')deffoo ():Print('In the foo') bar () foo ()

Higher order functions: that is, passing a function name as an argument to a function is similar to passing a variable name to a function.

#Higher order function: pass a function name as an argument to a functionImport TimedefBar (): Time.sleep (3)#pause for 3 seconds    Print('In the bar')defText1 (fun): Start_time= Time.time ()#Start TimeFun () stop_time= Time.time ()#End Time    Print('The fun time is %s'% (Stop_time-start_time))#calculate the time spent in fun ()Text1 (BAR)#Pass the function name indefbar2 (): Time.sleep (3)    Print('In the bar2')defText2 (fun):Print(Fun)returnfunbar2=Text2 (BAR2) bar2 ()

The function of higher order function can be seen: in the case of the source code of the function is not changed, to add the function of timing

Nested functions:

def foo ():     Print ('in thefoo')     def Bar ():         Print ('in thebar')    bar () foo ()

Combine the above three implementations of adorners:

Import TimedefTimer (func):#timer (Text1) func=text1 adorner function    defWrapper (*args,**Kwargs): Start_time=time.time () func ()#Run Text1Stop_time =time.time ()Print('The Fun run time is %s'% (stop_time-start_time)) returnWrapper@timer#Text1 = Timer (Text1) This step is to pass the Text1 into the timerdefText1 (): Time.sleep (1)    Print('The IS Text1') Text1 ()

Adorner with parameters:

USER,PASSWD ='Alex','1234'defAuth (outh_type):Print('auth func:', Outh_type)defOuth_wrapper (func):defWrapper (*args,**Kwargs):Print('wrapper func args:', *args,**Kwargs)ifOuth_type = ='Local': Username= Input ('Username:'. Strip ()) password= Input ('Password:'. Strip ())ifuser = = Username andpasswd = =Password:Print('\033[32;1muser has passed authentication\033[0m') Res= Func (*args,*Kwargs)Print('--After authentication')                    returnResElse: Exit ("\033[31;1minvalid username or password\033[0m")            elifOuth_type = ='LDAP':                Print('Knitting')        returnwrapperreturnOuth_wrapper@auth (Outh_type='Local')defindex ():Print('welcom to index page') index ()

Http://www.cnblogs.com/wupeiqi/articles/4980620.html

Python full stack development five iterator builder decorator

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.