|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- '''
- 目的:通过迭代器对象将需要信息存储到一个对象,并实时显示,减小时间和空间开销
- '''
- import requests
- from collections.abc import Iterator,Iterable
- class weatherIterator(Iterator):
- def __init__(self,cities):
- self.cities = cities
- self.index = 0
- def getweather(self,city):
- r = requests.get(r'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 weatherIterable(Iterable):
- def __init__(self,cities):
- self.cities = cities
- def __iter__(self):
- return weatherIterator(self.cities)
- for x in weatherIterable(['北京','上海','南京']):
- print(x)
- '''
- 提问与思考:
- 1、for循环工作机制:可迭代对象通过调用自身的__iter__()方法生成迭代器,
- 迭代器对象通过__next__()方法,进行迭代访问,迭代完毕最后抛出异常StopIteration
- '''
复制代码 |
|