Suppose I have the following class:
class MyGen(object):
def next(self):
return X()
def send(self, x):
return f(x)
Is it possible to express it as a single function, using the yield
keyword? Suppose I have g = MyGen()
. Note that g.next()
shouldn't call f()
, and g.send(x)
shouldn't call X()
, b开发者_Python百科ut f()
and X()
could share some code.
This code will be almost equivalent:
def my_gen(x=None):
while True:
if x is None:
x = yield X()
else:
x = yield f(x)
One difference is that you can't send a value (other than None
) to a generator before calling next()
for the first time. Another difference is that sending None
won't trigger calling f()
, since the generator can't distinguish send(None)
and next()
.
Sven's formulation is exactly the way to go, I just wanted to add that if you want to know more about generators, coroutines and such in Python, this site is the place to go.
精彩评论