generator 高阶

# generator class 的 send 方法

def my_generator():
   send_value = "hi"
   while True:
       receive = yield send_value
       if receive == 'fuck you':
           break
       elif receive == None:
           send_value = 'fuck you too'

       else:
           send_value = str(receive) + '\n' + 'yeah, fuck you too'


g = my_generator()
print(next(g))
print(g.send('hi yaya'))
print(g.send('merry christmas'))


# generator class 的 throw 方法
# 指定 throw 错误

def my_another_generator():
   send_value = 'hi'
   while True:
       try:
           yield send_value
           yield 'I hate my life'
           yield 'me too'
           yield 'fancy that!'

       except TypeError:
           print('Avada Kadvra!')

       except ValueError:
           break



g2 = my_another_generator()
print(next(g2))
print(g2.throw(TypeError))   # so... 执行except同时 生成一个数值
print(next(g2))
print(g2.throw(TypeError))   # 由此可以看出,在throw 出TypeError的同时,try的内容不会执行,而 重新 进入while循环,因此输出'hi'

# 为制定 throw 错误

def my_final_generator():
   n = 1
   yield n
   while n <= 10:
       yield n
       n += 1

g3 = my_final_generator()

print(next(g3))
print(next(g3))
print(g3.throw(TypeError))
print(next(g3))     # 此时会抛出StopIteration,生成器停止

你可能感兴趣的:(generator 高阶)