我正在学习Python我没有得到一件事.考虑以下代码:
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
Run Code Online (Sandbox Code Playgroud)
和输出
index 0
2
index 1
1
index 2
0
index 3
Run Code Online (Sandbox Code Playgroud)
为什么getitem被召唤四次?
python ×1