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?
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 at 4:41