Python Basics (ii)

Source: Internet
Author: User
Tags for in range generator iterable

? Builder 1. What is a generator?

Through the list, we can create a list directly. However, because of memory limitations, the list capacity is certainly limited.? and, create a list of 1 million elements, not just the storage space, if we just need access to the front?? Elements, after that? What is the space that most elements occupy?? Wasted. So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, saving space from the volume. In Python, this is the mechanism for edge-loop computing, called the Builder: Generator.

2. Create a builder? Method 1

There are many kinds of methods to create a builder. The first form of the law is very simple, just a list? [] into ()

 for  in range (5)] Output:print2, 4, 6, 8] Input: Gfor in range ( 5  ) Output:print  (G) Result:<generator object <genexpr> at 0x03490ea0>

The difference between the creation of L and G is only the outermost [] and (), L is a list,? G is a builder. We can print out each element of L directly, but how do we print out every element of G? If you want to print it out, you can get the next one from the next () function. A return value:

 for  in range (5))print(Next (g)) Print(Next (G )) print (Next (G)) 024
 for  in range (5)) for in G:    print(i) 0 2468

The generator saves the algorithm, each tune? Next (g), the value of the next element of G is calculated until the last element is calculated, and when there are no more elements, the stopiteration exception is thrown. Of course, this constant adjustment? Next () is so perverted, right? For loop, because the builder is also an iterative object. So, after we've created a builder, it's basically never tuned? Next (), is it iterative with a for loop and does not need to be closed? Stopiteration exception.

Summarize

The generator is such a function, which remembers the position in the function body at the time of the last return. The first (or nth) tune of the generator function? The middle of the function, all local variables of the last tune are left intact.
The generator not only "remembers" its data state; the generator also "remembers" its location in flow control constructs (in imperative programming, this construct is not just a data value).
The characteristics of the generator:
1. Save Memory

2. When we iterate to the next sub-tune, the parameters of the so-called times are left behind, that is to say, the parameters of the whole function adjustment are reserved at the time of the order. Not the newly created

An iterator iteration is a type of access to a collection element. 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. 1. Can iterate objects

The data types for the For loop are as follows:
The. Class is a collection of data types, such as list, tuple, dict, set, str, and so on;
The class is generator, including the builder and the generatorfunction with yield.
These can be done directly? The object of the For loop is called an iterative object: Iterable.

2. Determine if you can iterate

Can Isinstance () determine if the object is a Iterable object:

Summarize

All objects that can be used for A for loop are iterable types;

All objects that can be used for the next () function are Iterator types

Collection data types such as list , dict , str, etc. are iterable but not Iterator , but can be via iter () function obtains a Iterator object.

Decorative Device

The adorner is often in the development of the program, the function, the good adorner, development efficiency such as? Tim Wing, so this is also Python? must ask the question, but for a lot of first contact with this knowledge? Speaking, this function is a bit around,? The class is directly around the past, and then? Ask to hang up, because the decorator is the basic knowledge of the development of the program, this will not, do not say you will Python, read it? Chapter to make sure you learn to decorate the device.

Start-ups have N business unit, 1 basic Platform Department?, the basic platform is responsible for providing the underlying functions, such as: Database operations, Redis tune, monitoring API and other functions. Business Department? When you make a basic function, simply adjust the functionality provided by the underlying platform. As follows:

defF1 ():Print('F1')defF2 ():Print('F2')deff3 ():Print('f3')deff4 ():Print('f4')
# ##############    Business Department?    the    ###############F1 () F2 () F3 () F4 ()###############    business unit? B    Tune-the basic platform provides functionality    ###############
F1 () F2 () F3 () F4 ()

The former company methodically entered, however, the previous development of the Foundation platform, when writing code did not pay attention to the validation-related issues,

That is, the functionality provided by the underlying platform can be made by any. Now it is necessary to refactor all the functions of the underlying platform and add a validation mechanism to all the functions provided by the platform, namely: Before the function, advanced? authentication.

?? Give it to low B, that's what he did:

Negotiate with each business unit, each business unit??? Write the code, and then verify the functionality of the underlying platform. Eh, so? There is no need to make any changes to the base platform. That's great, there's a time for the bubble girl?...

The day low B was expelled ...?? Give it to low BB, that's what he did:
 the ############### Basic platform provides the following features ############### 
defF1 ():#Verification 1 #Verification 2 #Verification 3Print('F1')defF2 ():#Verification 1 #Verification 2 #Verification 3 Print('F2')deff3 ():#Verification 1 #Verification 2 #Verification 3 Print('f3')deff4 ():#Verification 1 #Verification 2 #Verification 3 Print('f4')

############### Business Department? Constant ############### # # # Business? A tune-the function provided by the base platform # # #

After the week low BB was expelled ...?? Give it to the low BBB, he did it:
only the code in the underlying platform refactoring, other business department?? Need to make any changes#the ############## Basic platform provides the following features ###############defCheck_login ():
   #Verification 1
# verification 2
# Verification 3
PassdefF1 (): Check_login ()Print('F1')defF2 (): Check_login ()Print('F2')deff3 (): Check_login ()Print('f3')deff4 (): Check_login ()Print('f4')

?? Look at the realization of the low BBB, mouth? The happy smile of silk, the language weight?? Chat with low BBB for a day:?? Say: Write code to follow the principle of open closure, although in this principle is? to the object, but also to the functional programming, in short, it stipulates that the function code has been implemented is not allowed to be modified, but can be extended, that is: Closed: implemented function code block open: to expand development if the open closed principle should be? In the above requirements, then it is not allowed in the function F1, F2, F3, F4 internal into the code, the board gave Low BBB, the implementation of the case:
defW1 (func):definner ():#Verification 1    #Verification 2    #Verification 3func ()returnINNER@W1defF1 ():Print('F1') @w1defF2 ():Print('F2') @w1deff3 ():Print('f3') @w1deff4 ():Print('f4')

For the above code, but also only the basic platform code into the change, you can achieve in the other? Function F1 F2 F3 f4 before the "verify" operation, and the other business unit?? Any action is required.
LOWBBB, what is the internal principle of this piece of code?
?? Are you going to lowbbb suddenly? The machine fell to the ground, and the screensaver was lowbbb? Friend photo?,??? Watch, grinning, decide to make a good friend with LOWBBB.
The detailed start explains:
Take F1 alone as an example:

defW1 (func):definner ():#Verification 1        #Verification 2        #Verification 3func ()returnINNER@W1defF1 ():Print('F1')
The Python interpreter interprets the code from top to bottom in the following steps:
1. Def W1 (func): ==> load W1 function into memory
2. @w1
Yes, the interpreter will only interpret the two lines of code from the table, because the function will not be in the code until it is tuned.

From the table to see the interpreter will really take the two sentences, but @w1 this sentence code? Chapter, the @ function name is Python's syntax sugar.
The above example @w1 inside will hold?? Operation: W1 function
The W1 function, and the @w1 function as the parameters of the W1 function, namely: @w1 equivalent to W1 (F1), so the internal will be to hold?:definner ():#Verification 1##验证 2##验证 3F1 ()#func is a parameter, at which time Func equals F1 returnInner#The returned Inner,inner represents the function, and the function is actually to plug the original F1 function into another function.The return value of the W1 will be assigned to the function name of @w1 under the W1 function return value F1 The return value of W1 will be re-assigned to F1, namely: New F1=defInner ():
#Verification 1##验证 2##验证 3    Original F1 ()returninner So, in the future Business department? When you want to hold the F1 function, the new F1 function will be used to validate the new F1 function, then the original F1 function, then return the original F1 function to the business tuning. So, to come, that is, to take the function of verification, F1 the contents of the original function, and return the value of the original F1 function back to the business tune? LOWBBB, are you clear? If not, I'll go to your house at night to help you solve it!!!
3. Re-discussion of adorners
#Define functions: Complete package datadefMakebold (FN):defwrapped ():return    "<b>"+ fn () +"</b>"                    returnWrapped#Define functions: Complete package datadefmakeitalic (FN):defwrapped ():return    "<i>"+ fn () +"</i>"                    returnWrapped@makebolddeftest1 ():return    "Hello world-1"@makeItalicdeftest2 ():return    "Hello world-2"@makeBold @makeItalicdeftest3 ():return    "Hello world-3"Print(Test1 ()))Print(Test2 ()))Print(Test3 ())) Transport results:<b>hello world-1</b> <i>hello world-2</i> <b><i>hello world-3</i></b >
4. Adorner (decorator) function 1. Cited?? Log 2. Function time Statistics 3. Pre-function processing 4. Post function Cleanup function 5. Permission checks and other scenarios 6. Cache 5. Decorator Example 1: The function of the parameter
 fromTimeImportCTime, SleepdefTimefun (func):defWrappedfunc ():Print("%s called at%s"% (func.__name__, CTime ())) Func ()returnWrappedfunc@timefundeffoo ():Print("I am Foo") foo () Sleep (2) foo ()
The above code understands that the adorner execution behavior can be understood as
Foo = timefun (foo)
#foo先作为参数赋值给func后, Foo receives a pointer to the Wrappedfuncfoo returned by Timefun ()
#调 foo (), which is the equivalent of Wrappedfunc () #内部函数wrappedfunc被引?, so the Func variable (? by variable) of the external function is not released
#func? The original Foo function object is saved

Python Basics (ii)

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.