1

If I have a class like this:

class Account:
   def __init__(self):
       self.transactions = []
   def __getitem__(self, index):
       return self.transactions[index]

I understand how the __getitem__ method is used to get a list (or other) index, such as the following:

>>> a = Account()
>>> a.transactions.append(1)
>>> a.transactions.append(2)
>>> a[1]
2

But how does it account for the following?

>>> for item in a:
...     print (item)
... 
1
2

How does python 'know' in the forloop how to use the correct index?

David542
  • 104,438
  • 178
  • 489
  • 842
  • May be of relevance: https://stackoverflow.com/questions/1292189/how-does-a-python-for-loop-with-iterable-work-for-party-in-feed-entry/57816761#57816761 – MisterMiyagi Oct 12 '19 at 04:41
  • https://docs.python.org/2/reference/datamodel.html#object.__getitem__ says that `Note for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.` – Dashadower Oct 12 '19 at 04:41

0 Answers0