+ 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.
9 Respostas
+ 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)
+ 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!
+ 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
+ 3
Anna we can do :
def __iter__(self) :
yield from self.itbl
+ 3
+ 2
Now, I got this, the 10th is causing a TypeError because an object isn't a suitable type for that iter() function.
+ 2
i find oop in python extremely confusing :(
+ 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.
+ 2
Abdul Samad thanks! :D