简体   繁体   English

我可以将其表示为生成器/协同程序吗?

[英]Can I express this as a generator / coroutine?

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? 是否可以使用yield关键字将其表示为单个函数? Suppose I have g = MyGen() . 假设我有g = MyGen() Note that g.next() shouldn't call f() , and g.send(x) shouldn't call X() , but f() and X() could share some code. 请注意, g.next()不应该调用f() ,而g.send(x)不应该调用X() ,但f()X()可以共享一些代码。

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. 一个区别是,在第一次调用next()之前,您不能向生成器发送值(除None )。 Another difference is that sending None won't trigger calling f() , since the generator can't distinguish send(None) and next() . 另一个区别是发送None不会触发调用f() ,因为生成器无法区分send(None)next()

Sven的配方正是要走的路,我只是想补充一点,如果你想了解更多有关Python中的生成器,协程等的信息,那么这个网站就是你要去的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM