python的item循环方法_python – for循环中的__getitem__调用

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值