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