阅读背景:

python进阶强化-3

来源:互联网 

1、如何实现可迭代对象和迭代器对象



# /usr/bin/env python
# -*- coding:utf-8 -*-
# Author : yimi

#如何实现可迭代对象和迭代器对象
import requests
from collections import Iterable,Iterator
class WeatherIterator(Iterator):
    def __init__(self,cities):
        self.cities = cities
        self.index = 0

    def getWeather(city):
        r = requests.get(u'https://wthrcdn.etouch.cn/weather_mini?city=' + city)
        data = r.json()['data']['forecast'][0]
        return '%s: %s, %s' % (city,data['low'],data['high'])
    # print getWeather(u'北京')
    # print getWeather(u'上海')
    def next(self):
        if self.index == len(self.cities):
            raise StopIteration
        city = self.cities[self.index]
        self.index += 1
        return self.getWeather()

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'贵港',u'重庆']):
    print(x)
# /usr/bin/env pyt



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: