2

Python 2.7でこのようなことをする方法はありますか?

def scaleit(g, k):
  for item in g:
    yield item*k

promise = ??????
# defines a generator for reference but not use:
# other functions can make use of it,
# but it requires a call to promise.fulfill() to
# define what the generator is going to yield;
# promise raises an error if next() is called 
# before the promise is fulfilled

f = scaleit(promise, 3)
promise.fulfill(range(10))

for item in f:
  print item
4

3 に答える 3

2

これは、あなたの望むことですか?

def scaleit(g, k):
  for item in g:
    yield item * k

class Promise(object):
    def __init__(self):
        self.g = None

    def fulfill(self, g):
        self.g = iter(g)

    def __iter__(self):
        return self

    def next(self):
        return next(self.g)

promise = Promise()

f = scaleit(promise, 3)
promise.fulfill(range(10))

for item in f:
  print item
于 2013-04-26T15:24:14.450 に答える
1

send()ジェネレーターのメソッドが必要だと思います:

def gen():
    reply = yield None
    if not reply:  # reply will be None if send() wasn't called
        raise ValueError("promise not fulfilled")
    yield 5

g1 = gen()
next(g1)  # advance to the first yield
g1.send(True)
print(next(g1))  # prints 5

g2 = gen()
next(g2)
# forget to send
print(next(g2))  # raises ValueError
于 2013-04-26T15:24:10.313 に答える