+ 4

Regarding __iter__ Magic Method in Python OOP

https://code.sololearn.com/c2n4UI9P4GE4/?ref=app This is the code with which I'm having some problem. The problem is the 10th line, why it is causing a TypeError? Whereas the 8th line is working fine. Aren't both of them supposed to perform the same task? It would be very nice of you if you helps me.

30th Jun 2019, 2:31 PM
Abdul S Ansari
Abdul S Ansari - avatar
9 Réponses
+ 6
def __iter__(self): for item in self.itbl: yield item obj = Demolist([1,2,3]) x = iter(obj) for n in x: print(n)
30th Jun 2019, 2:56 PM
Anna
Anna - avatar
+ 4
I think it's this: You're missing the __next__() method. (in python2 just next()) This might help: https://stackoverflow.com/questions/40923522/JUMP_LINK__&&__python__&&__JUMP_LINK-defining-an-iterator-class-failed-with-iter-returned-non-iterator-of If that doesn't help check this out: https://help.semmle.com/wiki/display/PYTHON/__iter__+method+returns+a+non-iterator I hope any of those help!
30th Jun 2019, 2:52 PM
Paul Grasser
Paul Grasser - avatar
+ 4
Check this two codes, you will maybe understand how to use iter function! __iter__ must return an iterator. Example : Liste = list(range(10)) iterable = iter(Liste) #returns iterator print(next(iterable)) #outputs 0 print(next(iterable)) #outputs 1 #... Etc So there is is another magic method __next__ https://code.sololearn.com/cAIE9Q5eaxzX/?ref=app https://code.sololearn.com/cVNgGs49bku3/?ref=app
30th Jun 2019, 2:54 PM
Théophile
Théophile - avatar
+ 3
Anna we can do : def __iter__(self) : yield from self.itbl
30th Jun 2019, 3:06 PM
Théophile
Théophile - avatar
1st Jul 2019, 2:27 PM
Abdul S Ansari
Abdul S Ansari - avatar
+ 2
Now, I got this, the 10th is causing a TypeError because an object isn't a suitable type for that iter() function.
1st Jul 2019, 2:32 PM
Abdul S Ansari
Abdul S Ansari - avatar
+ 2
i find oop in python extremely confusing :(
6th Jul 2019, 5:40 AM
HydrationDash
HydrationDash - avatar
+ 2
HydrationDash In start I was too but now I'm okay with it. And sololearn's explanation on some topics isn't wide enough to understand all the concepts more and more clearly. I prefer you to study OOP with YouTube and from some other websites alongside with SL.
6th Jul 2019, 8:51 AM
Abdul S Ansari
Abdul S Ansari - avatar
+ 2
Abdul Samad thanks! :D
6th Jul 2019, 12:24 PM
HydrationDash
HydrationDash - avatar