Python learn three-name-decorators, iterators, generators
First, the decoration device
Decoration, as the name implies is in the original on the basis of landscaping and perfection, the device refers to the function, so that the adorner is a decorative function, that is, do not change the original function of the code and call the method of the original function of the function of the perfect. The core principle is actually using closures.
Format @ keyword + decoration function
Be decorated function ()
Note: The @ line must be written on the head and is directly above the decorated function
According to the form can be divided into: non-parametric adorner and a parametric adorner, a reference decorator is to add parameters to the adorner
The following example is a non-parametric adorner that adds the function of statistic run time to the original function
import time# define adorner def timer (func): def wrapper (*args,**kwargs): start_time = Time.time () res = func (*args,**kwargs) stop_time = time.time () print ("run time is %s" % (stop_time-start_time)) return res return wrapper #调用装饰器 @timerdef index () : l = [] for i in range (10000000): l.append (i) #调用阶段 index ()
The following is a parametric adorner that implements a simple authentication function, #数字表示程序依次执行顺序
Def auth2 (auth_type): #1 #3 def auth (func): #4 #6 def wrapper (*args,**kwargs): #7 #10 if auth_type == ' file ': #11 name=input (' username : ') Password=input (' password: ') if name == ' zhejiangF4 ' and password == ' 666 ': print (' Auth successfull ') &nbsP; res=func (*args,**kwargs) return res else: print (' Auth error ') elif auth_type == ' SQL ': #12 print (' nothing! ') #13 return wrapper #8 return auth #5 @auth2 (auth_type= ' sql ') #2def index (): print (' Welcome to inex page ') index () #9
Second, iterators
an iterator (iterator) is an object that can be used to traverse some or all of the elements in a standard template's container, and each iterator object represents a definite address in the containers . ------Baidu Encyclopedia
Iterative: As long as the object itself has a __iter__ method, it is an iterative
The __iter__ method under the execution object, the result is the iterator
Why use iterators:
Advantages
1: iterators provide a way to not rely on an index, so that you can iterate over objects that are not indexed (dictionaries, collections, files)
2: iterators are compared with lists, iterators are lazy and more memory-saving
Disadvantages:
1: Unable to get the length of the iterator, the use of the list index value is not as flexible
2: Disposable, can only back value, can not be inverted value
To see if an S object is an iterator: print (Isinstance (s,iterator)) returns True is an iterator
From collections import iterable,iterators= ' Hello ' l=[1,2,3]t= (d={' a ': 1}set1={1,2,3,4}f=open (' a.txt ')
S.__ITER__ () l.__iter__ () t.__iter__ () d.__iter__ () set1.__iter__ () f.__iter__ () print (Isinstance (s,iterable)) print ( Isinstance (l,iterable)) print (Isinstance (t,iterable)) print (Isinstance (d,iterable)) print (Isinstance (SET1), iterable)) Print (Isinstance (f,iterable)) print (Isinstance (s,iterator)) print (Isinstance (l,iterator)) print ( Isinstance (T,iterator)) print (Isinstance (d,iterator)) print (Isinstance (set1,iterator)) print (Isinstance (f), Iterator))
The results of the operation are as follows:
650) this.width=650; "title=" Qq20170412194147.png "src=" https://s2.51cto.com/wyfs02/M01/8F/F7/ Wkiom1juepmylohfaaafnijnlna267.png "alt=" Wkiom1juepmylohfaaafnijnlna267.png "/>
As you can see, strings, lists, dictionaries, collections, tuples, and files are all iterative, but only the files are iterators
Third, generator
With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is 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, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.
The function contains the yield statement, which we call the generator function
What is the difference between yield and return?
return can only be returned once the function is completely finished, and yield can return multiple values
What does yield really do:
yield the function into a generator (the generator is an iterator)
The function pauses and continues the next run when the state is saved by yield
The following example is the application of two generators, one for constant input URL, constant parsing, and the other is to imitate the Linux Pipeline command (the essence is to pass the result of a function to the next function to do the processing, the implementation of relatively simple rough, many forgive, haha)
Example 1:
from urllib.request import urlopendef get (URL): while true: def index (): return urlopen (URL). Read () url = yield index () g = get (' HTTP// Www.baidu.com ') Next (g) Def run (): while true: url = input ("Please enter URL:") if ' HTTP//' not in url: Print (G.send (' http//' +url)) else: print (g.send (URL)) run ()
Def cat (filename): with open (filename, ' r ') as f: while True: line = f.readline () if not line: break else: yield linedef grep (String,lines): for line in lines: if string in line: yield lineg1 = cat (' A.txt ') g2 = grep (' Mac ', G1) if __name_ _ == ' __main__ ': m = input ("Please enter command:"). Strip () if m == "cat A.txt |grep mac ": for i in g2: print (i)
Supplement: Co-process
If the use of yield within a function is in the form of an expression, such as X=yield, then the function becomes the function of the co-process
Take a look at the example bar
def hello (func): def wrapper (*args,** Kwargs): res = func (*args,**kwargs) next (RES) return res return wrapper@hellodef eater (name): print ('%s start to eat food ' %name) food_list=[] while True: food=yield food_list print ('%s get %s ,to start eat ' % (name,food)) food_list.append (food) print (' Done ') E=eater (" Somebody ") Print (E.send (' chocolate ')) print (E.send (" banana "))
Python learn three-name-decorators, iterators, generators