Can a method within a class be generator?

爷,独闯天下 提交于 2019-12-06 22:46:42

问题


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()

回答1:


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.



来源:https://stackoverflow.com/questions/37349439/can-a-method-within-a-class-be-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!