Can someone please explain why the following code is giving
TypeError: iter() returned non-iterator of type 'counter' in python 3
This is working in python 2.7.3 without any error.
#!/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)
In python3.x you need to use __next__()
instead of next()
.
from What’s New In Python 3.0:
PEP 3114: the standard next() method has been renamed to __next__().
However, if you want your object to be iterable both in python 2.X and 3.X you can assign your next
function to the name __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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With