gpt4 book ai didi

python - __getitem__ 在 for 循环中调用

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:40 25 4
gpt4 key购买 nike

我正在学习 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

关于python - __getitem__ 在 for 循环中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8439482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com