实现可迭代对象和迭代器对象去查询天气

方式一:一个个的用函数实现

#_*_ encoding: utf-8 _*_   @author: ty  hery   2019/1/12
import requests
def getWeather(city):
    r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city='+city)
    data = r.json()['data']['forecast'][0]
    print( '%s: %s, %s' %(city,data['low'],data['high']))

getWeather('北京')
getWeather('长春')

方式二:构造一个可迭代对象和迭代器(Iterator)对象

In [7]: from collections import Iterable , Iterator

In [8]: Iterable.abstractmethods
Out[8]: frozenset({'iter'})

In [9]: Iterator.abstractmethods
Out[9]: frozenset({'next'})

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)
    print(r)
    data = r.json()['data']['forecast'][0]
    return '%s:%s ,%s' % (city, data['low'], data['high'])
    # data = r.json()    # ['data']['forecast'][0]
    # return data

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)
输出:
<Response [200]>
北京:低温 -6℃ ,高温 3℃
<Response [200]>
上海:低温 1℃ ,高温 8℃
<Response [200]>
广州:低温 9℃ ,高温 14℃
<Response [200]>
长春:低温 -18℃ ,高温 -12℃

posted @   ty1539  阅读(70)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示