Python高效编程 获取天气信息

获取天气信息

import requests


def getWeather(city):
    r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city)
    data = r.json()['data']['forecast'][0]
    return '{0}: {1}, {2}'.format(city, data['low'], data['high'])


print(getWeather('武汉'))
武汉: 低温 4℃, 高温 15℃

使用可迭代对象和迭代器输出信息

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("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)

注:慕课里写的是  def next(self):     内部其实调用的是def __next__(self):

用for in 的时候内部就会得到 迭代器对象  内部调用__iter__() 得到 迭代器对象,迭代器对象里面就不停的调用next()方法,只有for in 的时候才用不停触发next()

在迭代之前 先作一次转换 把可迭代对象s 转成 迭代器对象,就想作我迭代的就是一个迭代器,这样理利用看清事物的本质

迭代的过程中(for )就相当于 在不停的调迭代器对象的next()方法,

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值