可迭代对象与迭代器的区别:
- 可迭代对象包括迭代器
- 可迭代对象必须实现_iter_方法,迭代器必须实现_iter_方法和next方法
- 如果一个对象拥有_iter_方法,该对象为可迭代对象,如果一个对象拥有next方法,该对象为迭代器 可迭代对象包括:迭代器、序列(列表、元组、字符串等)、字典
获得城市天气:
- 实现一个迭代器对象WeatherIterator,next()方法,每次返回一个城市气温。
- 实现一个可迭代对象WeatherIterable,__iter__方法返回一个迭代对象。
import requests
#迭代器
class weatherIterlator(object):
def __init__(self, cities):
self.cities = cities
self.index = 0
def getWeather(self, city):
r = requests.get(u'http://http://www.weather.com.cn/'+city) #对某一固定方式进行get请求
data = r.json()['data']['forecast'][0]
return '%s:%s,%s'%(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():
def __init__(self, cities):
self.cities = cities
def __iter__(self): #可迭代对象标志
return weatherIterlator(self.cities)
#实例化
for x in weatherIterable([u'北京', u'上海', u'广州', u'西安', u'深圳']):
print(x)