+ 2
what is the error in this code and what is it's solution? (python code)
Following code has used iter method and next method inside class, in order to print no upto 5 from 1. class myclass: def __iter__(self): self.x=1 def __next__(self): y=self.x self.x+=1 return y obj=myclass() it=iter(obj) print(next(it)) print(next(it)) print(next(it)) print(next(it)) print(next(it)) The error is actually in line: it=iter(obj), it is saying that obj is not iterable type
10 Respostas
+ 1
here it is, you need a __iter__
https://code.sololearn.com/c50o5V4Q68et
+ 5
__iter__ is used for things like this:
for a in cls:
print(a)
or
list(cls)
class myclass:
def __init__(self):
self.x = 0
def __next__(self):
self.x+=1
return self.x
+ 1
The error is actually in line: it=iter(obj), it is saying that obj is not iterable type
+ 1
oh, because it's really not iterableđ
maybe try 'yield y' at the last line of nextđ€
+ 1
isn't helping, a new error appears now
+ 1
I'm trying itđ€
+ 1
thanks, i got this!
+ 1
error appeared due to the fact that iter method should return iterating object whenever used in a class.
+ 1
return self or return obj in iter method will solve this error. thanks everyone!
0
it.next()