import requests
from collections import Iterable, Iterator
import json
class WeaherIterator(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 '%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 WeaherIterable(Iterable):
def __init__(self,cities):
self.cities = cities
def __iter__(self):
return WeaherIterator(self.cities)
for x in WeaherIterable(['北京','上海', '长沙', '福州', '广州', '长春', '厦门']):
print(x)
WeaherIterable 类到底做了什么 没搞懂 我直接用 WeaherIterator 效果是一样的 。为啥要 WeaherIterable 实例传给 WeaherIterator 呢 视频上是说 这样可以延迟显示 有一个显示一个 但是我看直接用 WeaherIterator 也不是一下子显示出来的 也是一个个出来的 。这个 IMOC 上买的视频 有几节课听的一头雾水 求大神指点
from collections import Iterable, Iterator
import json
class WeaherIterator(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 '%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 WeaherIterable(Iterable):
def __init__(self,cities):
self.cities = cities
def __iter__(self):
return WeaherIterator(self.cities)
for x in WeaherIterable(['北京','上海', '长沙', '福州', '广州', '长春', '厦门']):
print(x)
WeaherIterable 类到底做了什么 没搞懂 我直接用 WeaherIterator 效果是一样的 。为啥要 WeaherIterable 实例传给 WeaherIterator 呢 视频上是说 这样可以延迟显示 有一个显示一个 但是我看直接用 WeaherIterator 也不是一下子显示出来的 也是一个个出来的 。这个 IMOC 上买的视频 有几节课听的一头雾水 求大神指点