繁体   English   中英

for循环中的__getitem__调用

[英]__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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM