Steven D'Aprano於 2013年7月2日星期二UTC+8上午6時09分18秒寫道: > On Mon, 01 Jul 2013 20:36:29 +0100, Marcin Szamotulski wrote: > > > > > Here is another example which I came across when playing with > > > generators, the first function is actually quite useful, the second > > > generator is the whole fun: > > > > > > from functools import wraps > > > def init(func): > > > """decorator which initialises the generator """ > > > @wraps(func) > > > def inner(*args, **kwargs): > > > g = func(*args, **kwargs) > > > g.send(None) > > > return g > > > return inner > > > > > > @init > > > def gen(func): > > > x = (yield) > > > while True: > > > x = (yield func(x)) > > > > > > > > > now if you have function f > > > def f(arg): > > > return arg**2 > > > > > > then calling f(5) is the same as > > > > > > g = gen(f) > > > g.send(5) > > > > > > > > I think you must be missing an important part of the trick, because > > calling f(5) returns 25. It's not: > > > > @gen > > def f(arg): > > return arg**2 > > > > > > because that raises TypeError. > > > > > > > > > > -- > > Steven
Lets be serious about generators and iterators. A generator can be used only once in a program is different from a a generator method of a class that can produce several instances with generators of the same kind but operated in each instance of the class. -- http://mail.python.org/mailman/listinfo/python-list