#coding:utf-8
from collections.abc import Iterator, Iterable
from random import randint
def get_weather(city) :
return city + str(randint(20, 35))
class WeatherIterator(Iterator):
def __init__(self, cities) :
self.cities = cities
self.index = 0
def __next__(self):
if self.index == len(self.cities) :
raise StopIteration
weather = get_weather(self.cities[self.index])
self.index += 1
return weather
class WeatherIterable(Iterable):
def __init__(self, cities) :
self.cities = cities
def __iter__(self) :
return WeatherIterator(self.cities)
city_weather = WeatherIterable(['北京','上海','广州','深圳','南京','天津'])
for w in city_weather:
print(w)
运行结果:
北京34
上海29
广州21
深圳35
南京35
天津29
[Finished in 0.4s]