zoukankan      html  css  js  c++  java
  • 实现可迭代对象和迭代器对象去查询天气

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

    #_*_ 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℃

    写入自己的博客中才能记得长久
  • 相关阅读:
    iOS开发---业务逻辑
    iOS 蓝牙功能 bluetooth
    iOS 企业版 安装失败 原因
    iOS 生命周期 -init、viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear、viewDidDisappear 区别和用途
    iOS 7 修改默认布局从status bar 底部开始
    企业打包时不能安装原因
    UISegmentedControl 功能简单 分析
    ios 推送 证书配置
    ios 获取手机设备信息
    创建quickstart报错
  • 原文地址:https://www.cnblogs.com/heris/p/14158131.html
Copyright © 2011-2022 走看看