0

I would like to create a Python class which should have a dynamic iterator function. That is, I would like to send the iterator function as a parameter instead of hardcoding it inside the class.

Here is an example class:

class fib:   
    def __init__(self, items, iter_function):
        self.iter_function = iter_function
        self.items = items

    def __iter__(self):
        self.iter_function(self.items)

with two example iterator functions:

def iter_func(items):
    for item in items:
        yield item

def iter_func2(items):
    for item in items:
        yield item*2

When I create an object with the following, I get an error:

a = fib([1,2,3],iter_func)
next(iter(a))

The error prints as:

----> 1 next(iter(a))

TypeError: iter() returned non-iterator of type 'NoneType'

Any ideas are appreciated.

Ahmadov
  • 1,567
  • 5
  • 31
  • 48
  • 2
    probably `def __iter__(self): self.iter_function(self.items)` => `def __iter__(self): return self.iter_function(self.items)` – Jean-François Fabre Jan 23 '18 at 14:00
  • 2
    You've missed the `return` at `self.iter_function(self.items)` line. But besides that you'd better to modify the `__next__` method instead of `__iter__`. – Mazdak Jan 23 '18 at 14:00
  • It is interesting. I thought that it should simply execute the given function which should then create a generator. Thanks. – Ahmadov Jan 23 '18 at 14:02

0 Answers0