是什么让 python 中的东西变得可迭代 [英] What makes something iterable in python

查看:51
本文介绍了是什么让 python 中的东西变得可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么让 Python 中的东西变得可迭代?IE.可以用 for

What makes something iterable in Python? ie. can loop over it with for

我可以在 Python 中创建一个可迭代的类吗?如果是这样,如何?

Is it possible for me to create an iterable class in Python? If so, how?

推荐答案

要使类可迭代,请编写一个返回迭代器的 __iter__() 方法:

To make a class iterable, write an __iter__() method that returns an iterator:

class MyList(object):
    def __init__(self):
        self.list = [42, 3.1415, "Hello World!"]
    def __iter__(self):
        return iter(self.list)

m = MyList()
for x in m:
    print(x)

印刷品

42
3.1415
Hello World!

该示例使用列表迭代器,但您也可以通过将 __iter__() 设为 generator 或通过返回定义 __next__() 方法.

The example uses a list iterator, but you could also write your own iterator by either making __iter__() a generator or by returning an instance of an iterator class that defines a __next__() method.

这篇关于是什么让 python 中的东西变得可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆