为什么视频需要两个类Iterator,和Iterable,我看代码里Iterator是继承Iterable的所以只要实现Iterator就行了

来源:3-2 如何实现可迭代对象和迭代器对象(2)

咸菜3

2017-10-28

#!/usr/bin/env python
#encoding:utf-8
import requests

from collections import Iterable,Iterator

#我看代码里Iterator是继承Iterable的所以只要实现Iterator就行了,不知道理解有没有问题

def getWeather(city):
   resp = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city='+city)
   weather = resp.json()['data']['forecast'][0]['type']
   print(u'city:%s weather:%s' %(city,weather))

class WeatherIterator(Iterator):
   def __init__(self,citys):
       self.citys=citys
       self.index=-1

   def next(self):
       if  self.index<len(self.citys)-2:
           self.index+=1
           city = self.citys[self.index]
           return getWeather(city)
       else:
           raise StopIteration

for x in WeatherIterator([u'北京',u'上海',u'广州',u'深圳',u'重庆']):
   print(x)

写回答

1回答

程序员硕

2017-10-29

强调他们的接口, 便于大家理解。

0
0

Python高效编程技巧实战

精选50个Python案例,源自实战,全面提升Python编程能力

2582 学习 · 360 问题

查看课程