如何实现可迭代对象和迭代器对象?

2019-02-09  本文已影响0人  Diolog

实际案例:

首先了解什么是可迭代对象:
经常接触到的可迭代对象有:List、String、Dict、Set、Tuple等
最好的判断方式为:对象的内置对象中存在iter 或者getitem(序列)方法。

首先我们实现天气获取的请求API:

#coding:utf8
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(u'http://wthrcdn.etouch.cn/weather_mini?city='+city)
    data = r.json()['data']['forecast'][0]
    return "{0}:{1},{2}".format(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(['常州','苏州','上海','南京']) :
  print(x)

输出结果:
常州:低温 0℃,高温 2℃
苏州:低温 0℃,高温 4℃
上海:低温 3℃,高温 5℃
南京:低温 -1℃,高温 1℃
上一篇下一篇

猜你喜欢

热点阅读