「python」生成器的高级应用send、close和throw方法
#send def gen_func(): # 这样写有两个作用1. 可以产出值, 2. 可以接收值(调用方传递进来的值) html = yield "http://projectsedu.com" #这样写的话就是接收值 print(html) yield 1 yield 2 return "bobby" #1. 生成器不只可以产出值,还可以接收值 #流程是,调用的产出yield值, #下一次调用send的值会到变量,html里面 if __name__ == "__main__": gen = gen_func() #首次,在调用send发送非none值之前,我们必须启动一次生成器, 方式有两种1. gen.send(None), 2. next(gen) url = gen.send(None) #download url html = "bobby" print(gen.send(html)) #send方法可以传递值进入生成器内部,同时还可以重启生成器执行到下一个yield位置 print(gen.send(html)) #1.启动生成器方式有两种, next(), send # print(next(gen)) # print(next(gen)) # print(next(gen)) # print(next(gen)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 # close def gen_func(): yield "http://projectsedu.com" yield 2 yield 3 return "bobby" if __name__ == "__main__": gen = gen_func() print(next(gen)) gen.close() #print(next(gen)) #生成器close掉之后,在调用next方法,就会抛异常 print("bobby") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 # throw def gen_func(): #1. 可以产出值, 2. 可以接收值(调用方传递进来的值) try: yield "http://projectsedu.com" except Exception as e: pass yield 2 yield 3 return "bobby" if __name__ == "__main__": gen = gen_func() print(next(gen)) gen.throw(Exception, "download error") #这个异常是扔到 yield "http://projectsedu.com"里面的,虽然他以及执行过。yield 2会跳过 print(next(gen)) gen.throw(Exception, "download error")
相关推荐
ericxieforever 2020-09-03
pengkunstone 2020-07-19
amazingbo 2020-06-28
RocNg 2020-04-18
逍遥友 2020-02-03
singer 2019-12-29
Kwong 2019-12-20
Kwong 2019-11-05
earthhouge 2020-08-15
Andrewjdw 2020-07-26
风吹夏天 2020-07-18
QCkiss 2020-06-04
FightFourEggs 2020-06-02
czsay 2020-06-01
troysps 2020-05-30
hanyujianke 2020-05-05
idning 2020-04-29
dbhllnr 2020-04-26
freedomfanye 2020-04-19