我正在学习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.
顺便说一句,如果你从列表中派生出来,你的实现会简单得多.你不需要__init __(),pop()或__getitem __(),而push可能只是append的另一个名字.此外,由于list具有非常好的__iter()__方法,因此将知道如何迭代它而不超过列表的末尾.
class Stack(list):
push = list.append
标签:python
来源: https://codeday.me/bug/20190716/1481754.html