+ 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

17th Sep 2018, 1:25 PM
Aditya Kulkarni
Aditya Kulkarni - avatar
10 Respostas
+ 1
here it is, you need a __iter__ https://code.sololearn.com/c50o5V4Q68et
17th Sep 2018, 1:59 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 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
17th Sep 2018, 2:02 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 1
The error is actually in line: it=iter(obj), it is saying that obj is not iterable type
17th Sep 2018, 1:46 PM
Aditya Kulkarni
Aditya Kulkarni - avatar
+ 1
oh, because it's really not iterable😂 maybe try 'yield y' at the last line of nextđŸ€”
17th Sep 2018, 1:48 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 1
isn't helping, a new error appears now
17th Sep 2018, 1:51 PM
Aditya Kulkarni
Aditya Kulkarni - avatar
+ 1
I'm trying itđŸ€”
17th Sep 2018, 1:52 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 1
thanks, i got this!
17th Sep 2018, 2:02 PM
Aditya Kulkarni
Aditya Kulkarni - avatar
+ 1
error appeared due to the fact that iter method should return iterating object whenever used in a class.
17th Sep 2018, 2:03 PM
Aditya Kulkarni
Aditya Kulkarni - avatar
+ 1
return self or return obj in iter method will solve this error. thanks everyone!
17th Sep 2018, 2:05 PM
Aditya Kulkarni
Aditya Kulkarni - avatar
0
it.next()
17th Sep 2018, 1:40 PM
Flandre Scarlet
Flandre Scarlet - avatar