类中的方法可以生成器吗? [英] Can a method within a class be generator?

查看:76
本文介绍了类中的方法可以生成器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类中使用方法作为生成器是否可接受/Pythonic?我发现的所有示例均在函数而非类中显示yield语句.

Is it acceptable/Pythonic to use a method in a class as a generator? All the examples I have found show the yield statement in a function, not in a class.

这是一个示例工作代码:

Here is an example working code:

class SomeClass(object):
    def first_ten(self):
        for i in range(10):
            yield i

    def test(self):
        for i in self.first_ten():
            print i

SomeClass().test()

推荐答案

是的,这完全正常.例如,通常用于实现 object.__iter__()方法使对象成为可迭代对象:

Yes, this is perfectly normal. For example, it is commonly used to implement an object.__iter__() method to make an object an iterable:

class SomeContainer(object):
    def __iter__(self):
        for elem in self._datastructure:
            if elem.visible:
                yield elem.value

但是,不要被那种通用的模式所限制;任何需要迭代的东西都是生成器方法的候选.

However, don't feel limited by that common pattern; anything that requires iteration is a candidate for a generator method.

这篇关于类中的方法可以生成器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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