python通过返回嵌入式iterable使类可迭代 [英] python make class iterable by returning embedded iterable

查看:59
本文介绍了python通过返回嵌入式iterable使类可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个类,该类具有可迭代的实例变量.我想通过迭代嵌入式可迭代对象来迭代类的实例.

I have a class in python, which has an iterable as instance variable. I want to iterate the instances of the class by iterating over the embedded iterable.

我实现了以下步骤:

def __iter__(self):
    return self._iterable.__iter__()

我真的不太喜欢在迭代器上调用__iter__()方法,因为它是一种特殊的方法.这是您将如何在python中解决此问题的方法,还是有更优雅的解决方案?

I don't really feel that comfortable calling the __iter__() method on the iterable, as it is a special method. Is this how you would solve this problem in python or is there a more elegant solution?

推荐答案

委派__iter__的最佳"方法是:

def __iter__(self):
    return iter(self._iterable)

或者,可能值得了解:

def __iter__(self):
    for item in self._iterable:
        yield item

在退还商品之前,您可以先摆弄些什么(例如,如果需要yield item * 2).

Which will let you fiddle with each item before returning it (ex, if you wanted yield item * 2).

正如@Lattyware在评论中提到的那样,PEP380(计划包含在Python 3.3中)将允许:

And as @Lattyware mentions in the comments, PEP380 (slated for inclusion in Python 3.3) will allow:

def __iter__(self):
    yield from self._iterable

请注意,执行以下操作可能很诱人:

Note that it may be tempting to do something like:

def __init__(self, iterable):
    self.__iter__ = iterable.__iter__

但是无效:iter(foo)直接绕过foo.__iter__调用type(foo)上的__iter__方法.考虑例如:

But this won't work: iter(foo) calls the __iter__ method on type(foo) directly, bypassing foo.__iter__. Consider, for example:

class SurprisingIter(object):
    def __init__(self):
        self.__iter__ = lambda self: iter("abc")

    def __iter__(self):
        return iter([1, 2, 3])

您希望list(SurprisingIter())返回["a", "b", "c"],但实际上返回[1, 2, 3].

You would expect that list(SurprisingIter()) would return ["a", "b", "c"], but it actually returns [1, 2, 3].

这篇关于python通过返回嵌入式iterable使类可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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