这个报错如何解决
来源:3-2 如何实现可迭代对象和迭代器对象(2)

穆步思
2017-12-26
写回答
3回答
-
盛年不再有
2017-12-28
def next(self)改成 def __next__(),看bug提示
10 -
慕士塔格
2018-01-05
几个错误吧:
按照迭代器协议,是需要实现__next__(),和__iter__()两个方法,Iterable是可迭代对象,__iter__是要求实现的,Iterator是迭代器,两个方法都需要实现,但内部是实现了__iter__,所以只需要重写__next__方法,因此,WeatherIterator里面的next方法需要修改成__next__;
WeatherIterator中的next方法`city = self.cities(self.index)`中的列表索引应该使用方括号;
next方法中,在返回self.__weather(city),此时,self.index已经自加了一次,这样就错位了,因此在__weather中需要减掉
最后可以运行的代码如下:
from collections import Iterable, Iterator class WeatherIterator(Iterator): def __init__(self, cities): self.cities = cities self.index = 0 def __weather(self, city): # 修改处 number = self.index-1 data = [{'北京': 30}, {'南京': 23}, {'上海': 21}, {'海南': 10}] print(data[number][city]) # next修改为__next__ def __next__(self): if self.index == len(self.cities): raise StopIteration print(self.index) # 修改处,self.cities(self.index)修改为方括号 city = self.cities[self.index] print(city) self.index += 1 return self.__weather(city) # def __iter__(self): # return self class WeatherIterable(Iterable): def __init__(self, cities): self.cities = cities def __iter__(self): return WeatherIterator(self.cities) for i in WeatherIterable(['北京', '南京', '上海', '海南']): print(i)
00 -
chipinzhen
2017-12-27
你的__weather函数当中都没有返回值 你加上以后再试试看看
00
相似问题