劳动人民万岁(拒绝惰性)------- 浅谈迭代对象(Iterable) 迭代器(Iterator)

一.前戏

  问题:如果一次抓取所有城市天气 再显示,显示第一个城市气温时有很高的延时,并且很浪费储存空间

  解决方案:以“用时访问”策略,并且能把说有城市气温封装到一个对象里,可用for一句进行迭代

二.上码

# -*- coding: utf-8 -*-
import requests
from collections import Iterable, Iterator # 可迭代对象 迭代器 (凡是可以for循环的,都是Iterable 凡是可以next()的,都是Iterator)


class WeatherIterator(Iterator): # 迭代器
def __init__(self, cites):
self.cites = cites
self.index = 0

def getweather(self, city):
w = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city) # 获取天气数据
data = w.json()['data']['forecast'][0]
return '%s:%s,%s' % (city, data['low'], data['high'])

# def __iter__(self):
# return self
def __next__(self):
if self.index == len(self.cites):
raise StopIteration # 迭代完成抛出异常
city = self.cites[self.index]
self.index += 1
return self.getweather(city)


class WeatherIterable(Iterable): # 可迭代对象
def __init__(self, cites):
self.cites = cites

def __iter__(self):
WeatherIterator(self.cites)


for x in WeatherIterator([u'北京', u'上海', u'广州', u'成都', u'天津', u'海南']):
print(x)

------------------------------------------------------备注----------------------------------------------------------------------------

# raise语法格式如下:
#
# raise [Exception [, args [, traceback]]]
# 语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。
#
# 最后一个参数是可选的(在实践中很少使用),如果存在,是跟踪异常对象。
# 当程序出现错误,python会自动引发异常,也可以通过raise显示地引发异常。一旦执行了raise语句,raise后面的语句将不能执行。
迭代器是一个对象,而生成器是一个函数,迭代器和生成器是python中两个非常强大的特性,编写程序时你可以不使用生成器达到同样的效果,但是生成器让你的程序更加pythonic。
创建生成器非常简单,只要在函数中加入yield语句即可。函数中每次使用yield产生一个值,函数就返回该值,然后停止执行,等待被激活,被激活后继续在原来的位置执行。

猜你喜欢

转载自www.cnblogs.com/jum-bolg/p/10803939.html