python迭代器两个基本方法,构建一个基本的Python迭代器

How would one create an iterative function (or iterator object) in python?

解决方案

Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and next(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.

Here's a simple example of a counter:

class Counter:

def __init__(self, low, high):

self.current = low

self.high = high

def __iter__(self):

return self

def next(self): # Python 3: def __next__(self)

if self.current > self.high:

raise StopIteration

else:

self.current += 1

return self.current - 1

for c in Counter(3, 8):

print c

This will print:

3

4

5

6

7

8

This is easier to write using a generator, as covered in a previous answer:

def counter(low, high):

current = low

while current <= high:

yield current

current += 1

for c in counter(3, 8):

print c

The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.

David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值