设为首页 加入收藏

TOP

Python迭代器的__iter__和__next__详细教程
2023-08-26 21:10:37 】 浏览:35
Tags:Python __iter__ __next__

在 Python 中,迭代器是一个实现了 __iter____next__ 方法的对象。__iter__ 方法返回迭代器对象自身,而 __next__ 方法返回下一个元素。换句话说,迭代器是一个可以逐个返回元素的对象。

下面是一个简单的迭代器示例,演示了如何实现 __iter____next__ 方法:

class MyIterator:
    def __init__(self, max_value):
        self.max_value = max_value
        self.current_value = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current_value >= self.max_value:
            raise StopIteration
        value = self.current_value
        self.current_value += 1
        return value

该迭代器可以生成从 0 到 max_value - 1 的整数序列。__iter__ 方法返回迭代器对象自身,而 __next__ 方法返回下一个元素。当没有更多元素时,__next__ 方法引发 StopIteration 异常,表示迭代已完成。

下面的示例演示了如何使用 MyIterator 类来迭代并打印从 0 到 4 的整数序列:

it = MyIterator(5)
for i in it:
    print(i)

输出:

0
1
2
3
4

在循环中,for 语句自动调用 iter() 函数获取迭代器,然后重复调用 __next__ 方法获取下一个元素,直到发生 StopIteration 异常为止。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇【pandas小技巧】--字符串转数值 下一篇Python安装uiautomator2

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目