今天来__next__和send, 改天来throw和close
class A: def __setattr__(self, key, val): print(‘set %s to %s‘%(key, val)) self.__dict__[key] = val def G(): e = A() i = 0 while 1: e.x = (yield i) print(‘ e.x is %s‘%e.x) i+=1 def p(s): print(‘ out put: %s\n‘% s) g = G() p(next(g)) p(next(g)) p(g.send(‘x1‘)) p(g.send(‘x2‘)) p(next(g))
结果:
>>> out put: 0 set x to None e.x is None out put: 1 set x to x1 e.x is x1 out put: 2 set x to x2 e.x is x2 out put: 3 set x to None e.x is None out put: 4
时间: 2024-12-28 02:25:26