生成器实现(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)
posted @ 2021-05-31 11:09  只管去做-王炸  阅读(117)  评论(0)    收藏  举报