2015-01-30 12 views
7

Czy ktoś mógłby wyjaśnić, dlaczego następujący kod dajeRodzaj błędu Iter - Python3

TypeError: iter() returned non-iterator of type 'counter' in python 3 

ten pracuje w python 2.7.3 bez żadnego błędu.

#!/usr/bin/python3 

class counter(object): 

    def __init__(self,size): 
     self.size=size 
     self.start=0 

    def __iter__(self): 
     print("called __iter__",self.size) 
     return self 

    def next(self): 
     if self.start < self.size: 
      self.start=self.start+1 
      return self.start 
     raise StopIteration 

c=counter(10) 
for x in c: 
    print(x) 

Odpowiedz

16

W python3.x trzeba użyć __next__() zamiast next().

z What’s New In Python 3.0:

PEP 3114: średnia Kolejna metoda() została zmieniona na __next __().

Jednakże, jeśli chcesz, aby Twój przedmiot będzie iterable zarówno w Pythona 2.X i 3.X można przypisać funkcję next nazwy __next__.

class counter(object): 

    def __init__(self,size): 
     self.size=size 
     self.start=0 

    def __iter__(self): 
     print("called __iter__",self.size) 
     return self 

    def next(self): 
     if self.start < self.size: 
      self.start=self.start+1 
      return self.start 
     raise StopIteration 

    __next__ = next # Python 3.X compatibility 
5

potrzebny jest __next__(self) nie obok:

def __next__(self):