Python3 报错求指点

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

ArtistLea

2018-02-22

我的代码:

import requests

from collections import Iterable, Iterator

class WeatherIterator(Iterator):
   def __init__(self,cities):
       self.cities = cities
       self.index = 0
   def getWeather(self,city):
       r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city)
       data = r.json()['data']['forecast'][0]
       return '%s: %s, %s %s' % (city,data['low'], data['high'],data['date'])
   def __next__(self):
       if self.index == len(self.cities):
           raise StopIteration
       city = self.cities[self.index]
       self.index += 1
       return self.getWeather(city)

class WeatherIterable(Iterable):
   def __init__(self,cities):
       self.cities = cities
   def __iter__(self):
       return WeatherIterable(self.cities)

for x in WeatherIterable([u'北京', u'上海', u'邯郸', u'西安']):
   print(x)


报错log:

Traceback (most recent call last):

  File "C:/Users/Artist/PycharmProjects/Artist/1. Python 高效实例/2-1 如何在列表,字段,集合中根据条件筛选数据.py", line 26, in <module>

    for x in WeatherIterable([u'北京', u'上海', u'邯郸', u'西安']):

TypeError: iter() returned non-iterator of type 'WeatherIterable'


写回答

1回答

ArtistLea

提问者

2018-02-22

汗。。自己书写错误。

以下可在Py3中执行。


import requests

from collections import Iterable, Iterator

class WeatherIterator():
  def __init__(self,cities):
      self.cities = cities
      self.index = 0
  def getWeather(self,city):
      r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city)
      data = r.json()['data']['forecast'][0]
      return '%s: %s, %s %s' % (city,data['low'], data['high'],data['date'])
  def __next__(self):
      if self.index == len(self.cities):
          raise StopIteration
      city = self.cities[self.index]
      self.index += 1
      return self.getWeather(city)

class WeatherIterable():
  def __init__(self,cities):
      self.cities = cities
  def __iter__(self):
      return WeatherIterator(self.cities)

for x in WeatherIterable(['北京', '上海', '邯郸', '西安']):
  print(x)

0
0

Python高效编程技巧实战

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

2582 学习 · 360 问题

查看课程