2015-01-30 15 views
7

Qualcuno può spiegare perché il seguente codice sta dandoTipo errore Iter - python3

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

Questo è il lavoro in Python 2.7.3 senza alcun errore.

#!/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) 

risposta

16

In python3.x è necessario utilizzare __next__() invece di next().

da What’s New In Python 3.0:

PEP 3114: il metodo standard next() è stato rinominato in __next __().

Tuttavia, se si desidera che l'oggetto sia iterabile sia in Python 2.xe 3.x è possibile assegnare la funzione next al nome __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

è necessario il __next__(self) non accanto:

def __next__(self):