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 for
loop 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 an IndexError
by 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__()
, and push
could be just another name for append
. Also, since list
has a perfectly good __iter()__
method, for
will know how to iterate it without going past the end of the list.
class Stack(list):
push = list.append
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With