1

I have a class like this

class MyClass:
    def __init__(self):
        self.test = [1,2,3]

Now I want to iterate over the test property like this:

a = MyClass()
for i in a:
    print(I)

So I've added another method to the class:

def __iter__(self):
    return self.test

Which doesn't work, unless I instead do this:

return iter(self.test)

I thought the for loop implicitly calls iter() behind the scenes and it's obviously capable of iterating over a normal list if I would do for i in a.test so obviously I'm not understanding something about using those functions. Would love some clarification

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
  • @jonrsharpe Anything wrong with [this](https://stackoverflow.com/questions/48124461/return-a-non-iterator-from-iter) as a dupe target? (You reopened after I added that question to the list; not sure if you noticed it) – Aran-Fey Jun 09 '18 at 15:40
  • A list is *iterable* but it's not an *iterator*, see e.g. https://stackoverflow.com/q/9884132/3001761 – jonrsharpe Jun 09 '18 at 15:41
  • @Aran-Fey I think that about covers it, sure; I misread with the first one I suggested, didn't realised you'd added to the list, sorry! – jonrsharpe Jun 09 '18 at 15:42
  • I don't see the answer I'm looking for in that question and answer, I'm looking for an explanation of the different uses of `iter` and `__iter__()` – Ofer Sadan Jun 09 '18 at 15:44
  • Not sure what your question is, then. The obvious difference between the two is that one is a function and the other is a method, so you can't do `__iter__('abc')` or `def iter(self):`. – Aran-Fey Jun 09 '18 at 15:46
  • @jonrsharpe doesn't the `list` have a `__next__` implemented? – Ofer Sadan Jun 09 '18 at 15:49
  • @OferSadan No, it doesn't. Lists are **iterables**, not **iterators**. – Aran-Fey Jun 09 '18 at 15:50
  • I understand now thank you, apologies for the confusion – Ofer Sadan Jun 09 '18 at 15:52
  • The third question added as duplicate now really answered my question – Ofer Sadan Jun 09 '18 at 15:54

0 Answers0