06 Feb 2017
下面以一个城市天气查询结果程序为例
为了实现上面的目标,我们可以使用collections的Iterable和Iterator
# 这两个对象的抽象接口如下 In [27]: from collections import Iterable, Iterator In [29]: Iterable.__abstractmethods__ Out[29]: frozenset({'__iter__'}) In [30]: Iterator.__abstractmethods__ Out[30]: frozenset({'next'})
从上面两个对象的抽象接口,我们就可以看出:
Iterable是用来构造迭代对象的
Iterator是用来构造迭代器的
#!/usr/bin/python # _*_ coding: utf-8 _*_ import requests from collections import Iterable, Iterator class WeatherIterator(Iterator): def __init__(self, cities): self.cities = cities self.index = 0 def getWeather(self, city): r = requests.get("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) if __name__ == "__main__": cities = [u'北京', u'上海', u'广州', u'深圳'] for x in WeatherIterable(cities): print x
执行过程
python getWeather.py 北京: 低温 -4℃, 高温 5℃ 上海: 低温 4℃, 高温 10℃ 广州: 低温 17℃, 高温 23℃ 深圳: 低温 16℃, 高温 23℃