python基础一 ------可迭代对象和迭代器对象

可迭代对象和迭代器对象;前者生成后者

比喻:10个硬币都可以一一数(迭代),放入到存钱罐(可以取钱的那种),那这个存钱罐就是一个迭代器对象

需求:从网络抓取各个城市气温信息,并依次显示
若依次抓取较多的城市,有较高的访问延迟,并且浪费存储空间,
希望以 “用时访问”策略 将所有的城市气温封装在
一个对象,可 用for语句迭代,如何解决?


方法:
一:实现一个迭代器对象,next()方法返回每一个城市气温
二:实现一个可迭代对象,__iter__方法返回一个迭代器对象

 1 import requests
 2 
 3 
 4 
 5 #print(getWeather(u"北京"))
 6 
 7 #创建一个迭代器
 8 from collections import Iterable,Iterator
 9 class WeatherIterator(Iterator):
10     def __init__(self,cities):
11         self.cities = cities
12         self.index  = 0
13     def getWeather(self,city):
14         r =requests.get(u"http://wthrcdn.etouch.cn/weather_mini?city=" + city)
15         data = r.json()['data']['forecast'][0]
16         return '{0}:{1},{2}'.format(city, data['low'],data['high'])
17 
18     def __next__(self):
19         if self.index == len(self.cities):
20             raise StopIteration
21         city = self.cities[self.index]
22         self.index += 1
23         return self.getWeather(city)
24 #生成一个可迭代对象
25 class WeatherIterable(Iterable):
26     def __init__(self,cities):
27         self.cities = cities
28     def __iter__(self):
29         return WeatherIterator(self.cities)
30 
31 for w in WeatherIterable([u"北京",u"肥城",u"呼和浩特"]):
32     print(w)
原文地址:https://www.cnblogs.com/ruoniao/p/6845648.html