迭代器
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
标签:__,异步,迭代,self,async,def From: https://www.cnblogs.com/zhuangjoo/p/17446569.html