Decorative Device
Generator
Iterators
first, the decoration device
adorners are functions, officially called syntactic sugars, except that the function can have a special meaning, adorners are used to decorate functions or classes, and adorners can be used to add actions before and after the function executes.
Grammar:
def wrapper (func): def result (): print (' before ') func () print (' after ') return Result@wrapperdef foo (): print (' foo ')
Instance:
#!/usr/bin/env python#-*-coding:utf-8-*-# __author__ = ' lvlibing ' Import timedef Timer (func): #timer (test1) func = t Est1 def deco (*args,**kwargs): start_time = Time.time () func (*args,**kwargs) #run test1 () stop_time = Time.time () print (' The Func run time is%s '% (start_time-stop_time)) return Deco@timer # test1 = Timer (test1) d EF test1 (): time.sleep (1) print (' in the Test1 ') @timer # test2 =timer (test2) = Deco test2 (name) = Deco (name) def tes T2 (name,age): print (' test2: ', Name,age) test1 () test2 (' LV ', 22)
Second, generator
A mechanism for calculating one side of the loop, called the generator: Generator.
There are a number of ways to create a generator. The first method is simple, as long as a list of the generated formula is []
changed ()
to create a generator:
1 2 3 4 5 6 |
>>> L = [x * x for x in range ( 10 )] >>> L [ 0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 >>> g = (x * x for x in range ( 10 )) >>> g <generator object <genexpr> at 0x1022ef630 > |
The L
difference between creating and making is g
only the outermost []
and, a ()
L
list, and g
a generator.
We can print out every element of the list directly, but how do we print out every element of generator?
If you want to print out one, you can next()
get the next return value of generator by using a function.
If a function definition contains a yield
keyword, then the function is no longer a normal function, but a generator.
Generator and functions do not have the same execution flow. The function is executed sequentially, the statement is encountered return
or the last line of the function is returned. The function that becomes generator, executes at each invocation next()
, encounters a yield
statement return, and executes again from the last statement returned yield
.
#!/usr/bin/env python#-*-coding:utf-8-*-# __author__ = ' lvlibing ' Import Time "" ' list generation ' A = (x * x for x in range) pr Int (a) for loop in A:print (loop) print (a.__next__ ()) # Print (a.__next__ ()) # Print (a.__next__ ()) "" "#Fibonacci斐波那契数列def Fibnaci (max): N,a,b = 0,0,1 while n < max: #print (b) #会执行return, get done return value yield B #函数定义中包含yield关键字 , the function becomes a generator and does not execute return #tuple = (b,a+b) # b = tuple[0],tuple[1] B = b,a+b n + = 1 return ' Done ' F=fibnaci (e) print (f) # Print (f.__next__ ()) ' For n ' f:print (n) "While true:try:t = Next (f) Print (' F: ', T) except stopiteration as E:print (' Generator return value: ', E.value) break# production consumer model, co-process (generator parallel Operation) def consumer (name): Print ('%s ready to eat steamed buns '%name) while True:baozhi = yield print (' bun [%s] came, was [%s] ate '% (BA Ozhi,name)) def producer (name): C1 = consumer (' a ') c2 = consumer (' B ') c1.__next__ () c2.__next__ () print (' Rear kitchen open Start to make buns ') for I in RanGE (x): Time.sleep (1) print (' Made 2 buns ') c1.send (i) #send方法调用前面函数yiled c2.send (i) #send方法调用前面函数yile Dproducer (' LV ')
Three, iterators
We already know that for
there are several types of data that can be directly acting on a loop:
A class is a collection of data types, such as,,, list
tuple
, and dict
set
str
so on;
One is generator
to include the generator and yield
the generator function with the band.
These objects, which can be directly applied to for
the loop, are called iterative objects: Iterable
.
You can use to isinstance()
determine whether an object is an Iterable
object.
An object that can be called by next()
a function and continually returns the next value is called an iterator:Iterator。
Generators are Iterator
objects, but,, list
dict
str
Though Iterable
they are, they are not Iterator
.
Turn list
, dict
and str
wait for the Iterable
Iterator
function to be used iter()
.
You may ask, why, list
dict
, str
etc. data types are not Iterator
?
This is because the Python Iterator
object represents a data stream, and the iterator object can be next()
called by the function and will return the next data continuously until there is no data to throw an StopIteration
error. You can think of this data stream as an ordered sequence, but we can't know the length of the sequence in advance, only by continuously using the next()
function to calculate the next data on demand, so Iterator
the calculation is lazy, and it will only be calculated when the next data needs to be returned.
Iterator
It can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.
Summary
Any object that can be used for for
the loop is a Iterable
type;
All objects that can be used for next()
functions are Iterator
types, which represent a sequence of lazy computations;
Collection data types such as list
, dict
,, and str
so on are Iterable
not Iterator
, however, you can iter()
get an object from a function Iterator
.
#!/usr/bin/env python#-*-coding:utf-8-*-# __author__ = ' lvlibing ' from collections import Iterablefrom collections Impor T Iteratorprint (Isinstance ((), iterable)) #Tprint (Isinstance ([], iterable)) #Tprint (Isinstance ({}, iterable)) #Tprint (Isinstance ({}, Iterator)) #Fprint (Isinstance ([], Iterator)) #Fprint (Isinstance (ITER ([]), Iterator)) #Tprint ( Isinstance (ITER ({}), Iterator)) #T "for x in [1,3,5,7,9]: pass equals it = ITER ([1,3,5,7,9]) while True: try: x = Next (it) except stopiteration: Break '
Python Route 4: Various types of device