[英]__getitem__ invocation in for loop
我正在学习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
和输出
index 0
2
index 1
1
index 2
0
index 3
为什么getitem被召唤四次?
for
循环不知道如何专门迭代你的对象因为你没有实现__iter__()
,所以它使用默认的迭代器。 这从索引0开始,直到它通过索引索引3得到IndexError
。参见http://effbot.org/zone/python-for-statement.htm 。
顺便说一句,如果你从list
派生出来,你的实现会简单得多。 你不需要__init__()
, pop()
或__getitem__()
,而push
可能只是append
另一个名字。 此外,由于list
有一个非常好的__iter()__
方法, for
将知道如何迭代它没有去过去的列表的末尾。
class Stack(list):
push = list.append
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.