迭代器
迭代器的目的是节省空间,可以循环
from collections import Iterable
from collections import Iterator
class Classmate(object):
def __init__(self):
self.name=list()
self.current_num=0
def add(self,name):
self.name.append(name)
def __iter__(self):
return self
def __next__(self):
if self.current_num<len(self.name):
ret =self.name[self.current_num]
self.current_num+=1
return ret
else:
raise StopIteration
classmate=Classmate()
classmate.add("laowang")
classmate.add("lisi")
classmate.add("wangwu")
# print(isinstance(classmate,Iterable))
# iter(classmate)
# classmate_iterator=iter(classmate)
# print(isinstance(classmate_iterator,Iterator))
for item in classmate:
print(item)
生成器
看上去的一个函数暂停执行
yield
通过next调用
send
yield完成多任务
import time
def task_1():
while True:
print("---1---")
time.sleep(0.1)
yield
def task_2():
while True:
print("---2---")
time.sleep(0.1)
yield
def main():
t1=task_1()
t2=task_2()
# 先让t1运行一会,当t1中遇到yield时候,在返回到23行
#然后执行t2,当他遇到yield时候,再次切换到t1
#这样t1/t2/t1/t2 交替运行,最终实现多任务...协程
while True:
next(t1)
next(t2)
if __name__=="__main__":
main()
gevent
import gevent
import time
import random
from gevent import monkey
# 有耗时操作时需要
monkey.patch_all()# 将程序中用到的耗时操作代码,换成gevent中自己实现的模块
def coroutine_work(coroutine_name):
for i in range(10):
print(coroutine_name,i)
time.sleep(random.random())
gevent.joinall([
gevent.spawn(coroutine_work,"work1"),
gevent.spawn(coroutine_work,"work2")
])
import urllib.request
import gevent
from gevent import monkey
monkey.patch_all()
def downloader(img_name,img_name2):
res=urllib.request.urlopen(img_name )
img=res.read()
with open("1.jpg","wb") as f:
f.write(img)
def main():
gevent.joinall([
gevent.spawn(downloader, "work1","https://rpic.douyucdn.cn/asrpic/190620/525207_2019.png/webpdy1"),
gevent.spawn(downloader, "work2","https://")
])
if __name__=="__main__":
main()