生成器实现(yield)
一、生成器既是迭代器对象也是可迭代对象
二、函数中含有yield关键字,即是生成器函数
三、自定义实现生成器进行for循环实例:
class WeatherIterable(Iterable):
def __init__(self, cities):
self.cities = cities
self.index = 0
def __iter__(self):
for _ in range(len(self.cities)):
yield self.get_weather()
self.index += 1
def get_weather(self):
city = self.cities[self.index]
url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
res = requests.get(url=url).json()
return city, res
it = WeatherIterable(['北京', '深圳', '广州'])
for x in it:
print(x)
浙公网安备 33010602011771号