如何为容器对象实现 __iter__(self) (Python) [英] How to implement __iter__(self) for a container object (Python)

查看:68
本文介绍了如何为容器对象实现 __iter__(self) (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个自定义容器对象.

I have written a custom container object.

根据这个页面,我需要在我的对象上实现此方法:

According to this page, I need to implement this method on my object:

__iter__(self)

但是,在跟踪迭代器类型的链接后在 Python 参考手册中,没有给出如何实现自己的示例.

However, upon following up the link to Iterator Types in the Python reference manual, there are no examples given of how to implement your own.

有人可以发布一个片段(或资源链接)来展示如何做到这一点吗?

Can someone post a snippet (or link to a resource), that shows how to do this?

我正在编写的容器是一个映射(即通过唯一键存储值).dicts 可以这样迭代:

The container I am writing, is a map (i.e. stores values by unique keys). dicts can be iterated like this:

for k, v in mydict.items()

在这种情况下,我需要能够在迭代器中返回两个元素(元组?).仍然不清楚如何实现这样的迭代器(尽管已经提供了几个答案).有人可以更详细地说明如何为类似地图的容器对象实现迭代器吗?(即像 dict 一样的自定义类)?

In this case I need to be able to return two elements (a tuple?) in the iterator. It is still not clear how to implement such an iterator (despite the several answers that have been kindly provided). Could someone please shed some more light on how to implement an iterator for a map-like container object? (i.e. a custom class that acts like a dict)?

推荐答案

我通常会使用生成器函数.每次使用 yield 语句时,它都会向序列中添加一项.

I normally would use a generator function. Each time you use a yield statement, it will add an item to the sequence.

下面将创建一个迭代器,它产生五个,然后是 some_list 中的每个项目.

The following will create an iterator that yields five, and then every item in some_list.

def __iter__(self):
   yield 5
   yield from some_list

3.3 之前,yield from 不存在,所以你必须这样做:

Pre-3.3, yield from didn't exist, so you would have to do:

def __iter__(self):
   yield 5
   for x in some_list:
      yield x

这篇关于如何为容器对象实现 __iter__(self) (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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