python basis of iterators generate decorator

basic concept

1. container (Container)

The container is a structure of a plurality of data elements are grouped together, the container element can be individually acquired iterations can be used innot inthe keyword is determined whether the element contained in the container. Such data structures typically all the elements stored in the memory (with some exceptions, not all elements are placed in memory, such as iterators and generator object) in Python, there is a common container objects:

  • list, and ....
  • set, frozensets, ….
  • dict, defaultdict, OrderedDict, Counter, ….
  • tuple, namedtuple, …
  • str

Container easier to understand, because you can see it as a box, a house, a cupboard, which can plug anything. From a technical point of view, when it can be used to ask whether an element is included therein, the object can be considered a container, such as list, set, tuples are container object.

2. iterables (iterable)

Anything that can return an iterator object can be called iterables

3. iterator (iterator)

So what iterator it? It is an object with a state, he can call on you next()to return the next value when the method of the container, any realized __iter__and __next__()object methods are iterator __iter__returns an iterator itself __next__returns the next value container, if there are no more elements in the container, then raise StopIteration, as it does not matter in the end it is how to achieve them.

Generator (Generator)

It contains a function of the yield keyword is a generator, also called the function generator function. When generating function is called, the code in the body of the function will not be executed, and returns an iterator. Each time a request value, the code generator will be executed until it encounters a return statement or expression yield. yield expression represents a value to be generated, return statement pledged to stop the generator. In other words, the generator is composed of two parts, the iterator generator function and the generator. Function generator is defined with the def statement, yield containing portion; iterator generator is part of the function returns. Both together called a generator.

 Iterators and generators

Application Example 1. iterator:

Copy the code
City = [ 'Beijing', 'Shanghai', 'tinajin', 'chongqin'] 
= ITER (City) 
Print (type (IT)) 
# Method a: using the next methods using an iterator 
print (it .__ next __ () ) 
Print (IT .__ Next __ ()) 

two: for loop iterator is used 
for X in IT: 
    Print (X)
Copy the code

2 is completed by the counter generator function similar functions

Copy the code
def generator(low,high):
    while low <= high:
        yield low
        low += 1
for i in generator(1,10):
    print(i,end='')


结果:12345678910
Copy the code

3. The generator produces an infinite number of values

Copy the code
def generator(start = 0):
    while True:
        yield start
        start += 1
for number in generator(4):
    print(number,end='')
    if number > 20:
        break
Copy the code

 4. List Builder

a = [i*2 for i in range(1,10)]
print(a)

结果: [2, 4, 6, 8, 10, 12, 14, 16, 18]

 Decorator

Requirements: 
 not modify the function of the source code to be decorated 
 can not be modified to be decorated is called by a function 
 satisfying the program to add functions in the above two cases 

 : the 
 <higher order function argument function + + + higher order function return value nested syntax function + sugar = decorator>

 1. Simple decorator

Copy the code
 1 import time
 2 def timer(func):
 3     def wrapper():
 4         start_time = time.time()
 5         func()
 6         stop_time = time.time()
 7         print("run time %s"%(stop_time-start_time))
 8     return wrapper
 9 @timer      #语法糖  test=timer(test)
10 def test():
11     time.sleep(3)
12     print("in the test")
13 test()
14
15 结果:
16 in the test
17 run time 3.000171661376953。
Copy the code
1.test represents the memory address of the function 
2.test () is a call to test the contents of this address, that is a function of the 

higher-order functions: 
1. a function name as arguments passed to another function ( "argument higher-order functions ") 
2. return value contains the function name (" higher-order function return value ") 
there said the function name, in fact, address of the function, the function name as argument, then that can the transfer function to another, and then do something inside another function. 

Nested functions: 
nested function refers to a function within the defined function, instead of calling 
a function and it can only be called the same level and higher variable or function. In other words: the inside and can call it like indentation and his outside, while the interior is not called. 

The test passed as parameters to the timer (), this time, the timer () inside, func = test, next, defines a warpper () function, but the call is not only stored in the memory, and 
the label is wrapper. In the timer () function returns the last wrapper () the address of the wrapper. Then put wrapper assigned to the test, then the test at this time is not the original test, the test is a function of the original label those bodies replaced, and replaced wrapper

2. decorated with parameter function

Copy the code
import time

def timer(func):
    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        stop_time = time.time()
        print(stop_time-start_time)
    return deco

@timer
def test(parameter):
    time.sleep(3)
    print("test is running")
test("添加参数")
Copy the code

3. More complex decorator

These two functions are run-time statistics, plus a layer functions to accept parameters, based on the concept of nested functions, in order to perform a function within, we must first execute the external function to call into the function

Copy the code
import time

def timer(parameter):

    def outer_wrapper(func):

        def wrapper(*args, **kwargs):
            if parameter == 'task1':
                start = time.time()
                func(*args, **kwargs)
                stop = time.time()
                print("the task1 run time is :", stop - start)
            elif parameter == 'task2':
                start = time.time()
                func(*args, **kwargs)
                stop = time.time()
                print("the task2 run time is :", stop - start)

        return wrapper

    return outer_wrapper

@timer(parameter='task1')
def task1():
    time.sleep(2)
    print("in the task1")

@timer(parameter='task2')
def task2():
    time.sleep(2)
    print("in the task2")

task1()
task2()

Guess you like

Origin www.cnblogs.com/zhichao123/p/11234134.html