Python 等待对象的价值是什么?

Python 等待对象的价值是什么?,python,async-await,Python,Async Await,在发布asyncio之前,我一直在使用基于生成器的协同程序 现在我尝试学习Python 3.5中引入的新async/await特性。这是我的一个测试程序 class Await3: def __init__(self, value): self.value = value def __await__(self): return iter([self.value, self.value, self.value]) async def main_co

在发布
asyncio
之前,我一直在使用基于生成器的协同程序

现在我尝试学习Python 3.5中引入的新
async/await
特性。这是我的一个测试程序

class Await3:
    def __init__(self, value):
        self.value = value
    def __await__(self):
        return iter([self.value, self.value, self.value])

async def main_coroutine():
    x = await Await3('ABC')
    print("x =", x)

def dummy_scheduler(cobj):
    snd = None
    try:
        while True:
            aw = cobj.send(snd)
            #snd = 42
            print("got:", aw)
    except StopIteration:
        print("stop")

dummy_scheduler(main_coroutine())
其产出是:

got: ABC
got: ABC
got: ABC
x = None
stop
x
的值是
await waitable\u object
表达式的结果。为什么此值
None
以及如何将其设置为所需的值

我所能找到的就是
await coutroutine()
的值是由协同程序的返回值决定的,但我的情况不是这样


取消注释
snd=42
不起作用。错误是
AttributeError:“list\u iterator”对象没有属性“send”

如果您要手动实现一个带有
\uuuuuuu wait\uuuuuu
方法的类,类实例上的
await
表达式的返回值将是用于在迭代器末尾构造
StopIteration
异常的任何参数,或者如果没有参数,则返回
None

您不能使用类似于返回iter(一些列表)的东西来控制
StopIteration
参数。您需要编写自己的迭代器。我想把它写成一个生成器,然后
返回
值:

class Await3:
    def __init__(self, value):
        self.value = value
    def __await__(self):
        yield self.value
        yield self.value
        yield self.value
        return whatever
这将抛出
StopIteration(无论什么)
来结束迭代,但是如果您想以简单的方式完成任务,那么您首先应该编写一个
async
函数