标签:http 迭代器 self sts requests json __next__ 实现 返回
可迭代对象实现__iter__方法,返回迭代器对象
迭代器对象实现__iter__方法,返回迭代器对象,实现__next__方法,进行迭代操作
自定义实现迭代器进行for循环实例:
import requests
from collections import Iterable, Iterator
# 实现自定义迭代器对象类
class WeatherIterator(Iterator):
def __init__(self, cities):
self.cities = cities
self.index = 0
def __next__(self):
if self.index == len(self.cities):
raise StopIteration
self.index += 1
return self.get_weather()
def get_weather(self):
city = self.cities[self.index-1]
url = ‘http://wthrcdn.etouch.cn/weather_mini?city=‘ + city
res = requests.get(url=url).json()
return city, res
# 实现自定义可迭代对象类
class WeatherIterable(Iterable):
def __init__(self, cities):
self.cities = cities
def __iter__(self):
return WeatherIterator(self.cities)
it = WeatherIterable([‘北京‘, ‘深圳‘, ‘广州‘])
for x in it:
print(x)
迭代器对象(Iterator)和可迭代对象(Itetable)
标签:http 迭代器 self sts requests json __next__ 实现 返回
原文地址:https://www.cnblogs.com/inflame/p/14830257.html