first edited October 27, 2017, Friday
Summary
I. Last Class review
Two. iterators
Three. Generator
Four. The co-process function
Homework
Summary today
Summary
References: Alex
- Iterators
- Generator
- Co-process function
I. Last Class review
- Decorative Device
- Non-parametric adorner
- With reference decorator
- The adorner prints the original function information
import timefrom functools import wraps #注意这个def timmer(func): @wraps(func) #还有这个 def wrapper(): start_time = time.time() func() stop_time = time.time() print(‘run time is %s ‘ % (stop_time - start_time)) return wrapper@timmer #index=timmer(index)def index(): ‘come from index‘ print(‘welcome to oldboy‘)index() #wrapper()print(index.__doc__) #.__doc__打印函数描述信息,具体不是很了解
Two. iterators
- An iterative
- As long as the object itself has a __iter__ method, it is an iterative
- Iterators
- i = A.iter() #i is an iterator
- Value can be obtained by __next__
b = {‘a‘:1,‘b‘:2,‘c‘:3}i = iter(b)while True: print(next(i))#注意:此方法会while会无限循环,报错异常 StopIteration
- Exception snapping
b = {‘a‘:1,‘b‘:2,‘c‘:3}i = iter(b)while True: try: #注意此行 print(next(i)) except StopIteration: #and this break # and this
- For loop mechanism
for key in d: #d即为d.__iter__() 迭代器放入原位置 print(key) #并且for循环具有异常捕捉的功能
- For loop Implementation iterator
b = {‘a‘:1,‘b‘:2,‘c‘:3}for i in b: print(i)
- Why use iterators
- Advantages
- Iterators provide a way to not rely on an index, so that you can iterate over objects that are not indexed (dictionaries, collections, files)
- Iterators are lazy calculations compared to lists, and more memory (Iterators have only one value at the same time in memory)
- Disadvantages
- Unable to get the length of the iterator, using a value that is less flexible than the list index
- One-time, can only be taken back to the value, can not be inverted value
- Viewing an Iterator object with an iterator
from collections import Iterable,Iterators = ‘hello‘l = [1,2,3]t = (1,2,3)d = {‘a‘:1}set1 = (1,2,3,4)f = open(‘a.txt‘)s.__iter__()l.__iter__()t.__iter__()d.__iter__()set1.__iter__()f.__iter__() #Iterable 为可迭代的print(isinstance(s,Iterable)) #isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。print(isinstance(l,Iterable))print(isinstance(t,Iterable))print(isinstance(d,Iterable))print(isinstance(set1,Iterable))print(isinstance(f,Iterable))
- See if it is an iterator
print(isinstance(s,Iterator)) #Iterator 为迭代器print(isinstance(l,Iterator))print(isinstance(t,Iterator))print(isinstance(d,Iterator))print(isinstance(set1,Iterator))print(isinstance(f,Iterator))
Three. Generator
- Definition: A generator is a function in which the package contains the keyword yield, which can turn the function into a sequence, returning multiple values
- What is the difference between a generator and return
- Return can return only once to the end of the function, and yield returns multiple values
- What did the yield really do?
- Yield turns the function into a generator (the generator is actually an iterator) (yield will encapsulate __next__ and __iter__ inside the function)
- Returns can only be returned once with return, and yield returns multiple times
- The state of the function while pausing and continuing the next run is saved by yield
def test(): print(‘one‘) yield 1 print(‘two‘) yield 2 print(‘three‘) yield 3g = test() #无输出,此时g为生成器,即把函数变成一个迭代器print(g) #<generator object test at 0x00000000027E91A8>res = next(g) #one next触发生成器的执行print(res) #1
- Yield specific application
def countdown(n): print(‘start countdown‘) while n >0: yield n n -= 1 print(‘done‘)g= countdown(5)print(next(g)) #start countdown 5print(next(g)) #4print(next(g)) #3print(next(g)) #2print(next(g)) #1print(next(g)) #done #会报错#for循环写法for i in g: print(i)#while循环写法while True: try: print(next(g)) except StopIteration: break
- Builder app
#惰性计算def func(): n = 0 while True: yield n n += 1f = func()print(next(f))
- The most basic implementation of the tail command
import timedef tail(file_path): with open(file_path,‘r‘) as f: f.seek(0,2) #光标移到最后 while True: line = f.readline() #读这一行 if not line: time.sleep(0.5) continue else: print line, #print 输出光标不换行tail(‘/tmp/a.txt‘)
- The tail command is implemented by the generator (Python2)
import timedef tail(file_path): with open(file_path,‘r‘) as f: f.seek(0,2) #光标移到最后 while True: line = f.readline() #读这一行 if not line: time.sleep(0.5) print ‘=======‘ continue else: yield lineg = tail(‘/tmp/a.txt‘) #函数变成一个生成器for line in g: print line,
- grep commands are implemented by the generator (Python2)
import timedef tail(file_path): with open(file_path,‘r‘) as f: f.seek(0,2) #光标移到最后 while True: line = f.readline() #读这一行 if not line: time.sleep(0.5) continue else: yield lineg = tail(‘/tmp/a.txt‘)for line in g: if ‘error‘ in line: print line,
- The grep command is implemented by the generator and has a flow concept
import timedef tail(file_path): with open(file_path,‘r‘) as f: f.seek(0,2) #光标移到最后 while True: line = f.readline() #读这一行 if not line: time.sleep(0.5) continue else: yield linedef grep(pattern,lines): #pattern 为grep所抓取的 lines为输入源 for line in lines: if pattern in line: print line,g = tail(‘/tmp/a.txt‘)grep(‘error‘,g)
- Tail, grep command final version
import time#定义阶段:定义两个生成器函数def tail(file_path): with open(file_path,‘r‘) as f: f.seek(0,2) #光标移到最后 while True: line = f.readline() #读这一行 if not line: time.sleep(0.5) continue else: yield linedef grep(pattern,lines): #pattern 为grep所抓取的 lines为输入源 for line in lines: if pattern in line: yield line#调用阶段:得到俩生成器对象g1 = tail(‘/tmp/a.txt‘)g2 = grep(‘error‘,g1)#使用阶段:next触发执行g2生成器函数for i in g2: print i,
Four. The co-process function
- Eat steamed buns
def 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(‘钢蛋‘)print(next(e))print(e.send(‘包子‘))print(e.send(‘韭菜包子‘)) #send 等同于next 有返回值,但是会把后面的参数传给当前行的yieldprint(e.send(‘馅饼‘))
Homework
- No
Summary today
- Ready to be sorted
Python Full Stack road Day21