I am learning Python I don’t get one thing. Consider this code:
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def __getitem__(self,index):
print "index",index
return self.items[index]
def __len__(self):
return len(self.items)
stack = Stack()
stack.push(2)
stack.push(1)
stack.push(0)
for item in stack:
print item
and the output
index 0
2
index 1
1
index 2
0
index 3
Why is getitem called four times?
The
forloop doesn’t know how to iterate over your object specifically because you have not implemented__iter__(), so it uses the default iterator. This starts at index 0 and goes until it gets anIndexErrorby asking for index 3. See http://effbot.org/zone/python-for-statement.htm.Your implementation would be a lot simpler if you derived from
list, by the way. You wouldn’t need__init__(),pop(), or__getitem__(), andpushcould be just another name forappend. Also, sincelisthas a perfectly good__iter()__method,forwill know how to iterate it without going past the end of the list.