Can a method within a class be generator?

2019-04-28 13:17发布

问题:

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:

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.



回答2:

As Martijn already wrote: it is perfectly acceptable.

A method is just a "bound function" (in Python 2 it is a simplification - a more elaborated answer you may find in this thread: What is the difference between a function, an unbound method and a bound method?).