迭代器与异步迭代器

迭代器

class Reader(object):
    """ 自定义异步迭代器(同时也是异步可迭代对象) """
    def __init__(self):
        self.count = 0
    def readline(self):
        # await asyncio.sleep(1)
        self.count += 1
        if self.count == 100:
            return None
        return self.count
    def __iter__(self):
        return self
    def __next__(self):
        val =self.readline()
        if val == None:
            raise StopAsyncIteration
        return val
def func():
    # 创建异步可迭代对象
    async_iter = Reader()
    # async for 必须要放在async def函数内,否则语法错误。
    for item in async_iter:
        print(item)
func()

异步迭代器

import asyncio
class Reader(object):
    """ 自定义异步迭代器(同时也是异步可迭代对象) """
    def __init__(self):
        self.count = 0
    async def readline(self):
        # await asyncio.sleep(1)
        self.count += 1
        if self.count == 100:
            return None
        return self.count
    def __aiter__(self):
        return self
    async def __anext__(self):
        val = await self.readline()
        if val == None:
            raise StopAsyncIteration
        return val
async def func():
    # 创建异步可迭代对象
    async_iter = Reader()
    # async for 必须要放在async def函数内,否则语法错误。
    async for item in async_iter:
        print(item)
asyncio.run(func())
View Code

 

posted @ 2023-05-31 16:30  壮九  阅读(14)  评论(0)    收藏  举报