首页 > 其他 > 详细

迭代器对象(Iterator)和可迭代对象(Itetable)

时间:2021-05-31 12:05:07      阅读:22      评论:0      收藏:0      [点我收藏+]

一、可迭代对象实现__iter__方法,返回迭代器对象

二、迭代器对象实现__iter__方法,返回迭代器对象,实现__next__方法,进行迭代操作

三、for循环执行的底层实现:首先调用可迭代对象的iter方法生成迭代器对象,再循环调用迭代器对象的next方法,直到抛出StopIteration错误,循环结束
  iter(WeatherIterable) -> it -> next(it) -> StopIteration

四、自定义实现迭代器进行for循环实例:

import requests
from collections import Iterable, Iterator

# 实现自定义迭代器对象类
class WeatherIterator(Iterator):
def __init__(self, cities):
self.cities = cities
self.index = 0

def __next__(self):
if self.index == len(self.cities):
raise StopIteration
self.index += 1
return self.get_weather()

def get_weather(self):
city = self.cities[self.index-1]
url = ‘http://wthrcdn.etouch.cn/weather_mini?city=‘ + city
res = requests.get(url=url).json()
return city, res

# 实现自定义可迭代对象类
class WeatherIterable(Iterable):
def __init__(self, cities):
self.cities = cities

def __iter__(self):
return WeatherIterator(self.cities)


it = WeatherIterable([‘北京‘, ‘深圳‘, ‘广州‘])
for x in it:
print(x)


迭代器对象(Iterator)和可迭代对象(Itetable)

原文:https://www.cnblogs.com/inflame/p/14830257.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!