V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
fangwenxue
V2EX  ›  问与答

Python async yield 问题

  •  
  •   fangwenxue · 2021-12-29 11:27:23 +08:00 · 940 次点击
    这是一个创建于 841 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import asyncio
    
    
    class A:
        data = [1, 2, 3]
    
        async def test(self):
            for i in self.data:
                yield i
    
    
    class B(A):
        flag = True
    
        async def test(self):
            if self.flag:
                # 怎么直接返回父类的 test 并打印 1 2 3
                yield super(B, self).test()
            else:
                pass
    
        async def run(self):
            async for i in self.test():
                # 打印不是 1 2 3 而是 async_generator
                print(i)
    
    
    asyncio.run(B().run())
    
    
    4 条回复    2021-12-29 14:35:08 +08:00
    ipwx
        1
    ipwx  
       2021-12-29 11:29:39 +08:00
    yield from
    ipwx
        2
    ipwx  
       2021-12-29 11:31:08 +08:00
    好吧 async 不能 yield from

    老老实实 async for ... in super().... yield
    chashao
        3
    chashao  
       2021-12-29 14:04:31 +08:00
    这样不知道对不对。。
    class A:
    data = [1, 2, 3]

    async def test(self):
    for i in self.data:
    yield i


    class B(A):
    flag = True

    def test(self):
    if self.flag:
    # 怎么直接返回父类的 test 并打印 1 2 3
    return super(B, self).test()
    else:
    pass

    async def run(self):
    async for i in self.test():
    # 打印不是 1 2 3 而是 async_generator
    print(i)

    asyncio.run(B().run())
    shyrock
        4
    shyrock  
       2021-12-29 14:35:08 +08:00
    async for 的功能是迭代一个异步可迭代对象。
    你写 async for i in self.test():就是迭代 B.test()。B.test()返回的是父类的一个异步生成器。所以迭代结果就是打印这个异步生成器对象了。
    如果你要迭代 A.test()的内容,改成这样就可以:
    async for i in super(B, self).test():
    print(i)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3453 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:24 · PVG 19:24 · LAX 04:24 · JFK 07:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.