-2

I am in a very strange situation. I know I can use a method class as a generator as I have done it before. In this other question Can a method within a class be generator? someone asks for the same thing and they say that yes, it can be done.

However, I get an error when I try it. Here is a minimal example:

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

a = SomeClass();
next(a.first_ten)

'method' object is not an iterator

why? How is this possible? Thank you edited: fixed code indentation

Vaaal88
  • 591
  • 1
  • 7
  • 25
  • why the negative vote? What is wrong with my question exactly? – Vaaal88 Sep 16 '18 at 10:06
  • The clue is in "'method' object is not an iterator"... you need to call the method... `it = a.first_ten()` then use such as `next(it)` for instance... or `for n in a.first_ten(): print(a)` etc.. – Jon Clements Sep 16 '18 at 10:10

1 Answers1

3

You need to call the method:

a = SomeClass()
it = a.first_ten()
next(it)

The reason for this is that the method is not itself a generator. It is a generator function that returns a new generator every time it is called.

The same applies for non-method generator functions as well. Note the types in this snippet:

>>> def f():
...     yield from range(10)
...
>>> type(f)
<class 'function'>
>>> type(f())
<class 'generator'>
Mikhail Burshteyn
  • 4,762
  • 14
  • 27