案例
某軟件要求,從網絡抓去各個城市氣溫信息,并依次顯示:
北京:15~20
天津:17~22
長春:12~18
……
如果一次抓取所有城市天氣再顯示,顯示第一個城市氣溫時,有很高的延時,并且浪費存儲空間。
我們期望以“用時訪問”的策略,并且能把所有城市氣溫封裝到一個對象里,可用for語句進行迭代。如何解決?
解析
Step1:實現一個迭代器對象WeatherIterator,
__next__
方法每次返回一個城市氣溫。
Step2:實現一個可迭代對象Weatherlterable,__iter__
方法返回一個迭代器對象。
# coding:utf8
from collections import Iterable, Iterator
import requests
class WeatherIterator(Iterator):
def __init__(self, cities):
self.cities = cities
self.index = 0
def getweather(self, city):
r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city)
data = r.json()['data']['forecast'][0]
return '%s:%s, %s' % (city, data['low'], data['high'])
def __next__(self):
if self.index == len(self.cities):
raise StopIteration
city = self.cities[self.index]
self.index += 1
return self.getweather(city)
class WeatherIterable(Iterable):
def __init__(self, cities):
self.cities = cities
def __iter__(self):
return WeatherIterator(self.cities)
for x in WeatherIterable([u'北京', u'深圳', u'長春', u'武漢']):
print(x)