0

i have homework and we need to do something like iterator, the func work great but the techer told he run the func with (t=Make_iterator()) like this, what i do wrong? tnx!

global x
x=-1

def Make_iterator(fn):
    global x
    x+=1
    return fn(x)

fn=lambda y:y*2

t=Make_iterator(fn)

print(t())

2 Answers 2

4

I think you want a closure, which is a function defined within the local namespace of anther function, so that it can access the outer function's variables:

def make_iterator(func):
    x = -1
    def helper():
        nonlocal x
        x += 1
        return func(x)
    return helper

The nonlocal statement allows the inner function to modify the variable declared in the outer function (otherwise you'd either get an error, or you'd bind your own local variable without changing the outer one). It was only added in Python 3, so if you're still using Python 2, you'll need to wrap the x value in a mutable data structure, like a list.

Another approach to the same idea is to write class, rather than a function. An instance of a class can be callable (just like a function) if the class defines a __call__ method:

class MyIterator(object):
    def __init__(self, func):
        self.index = -1
        self.func = func

    def __call__(self):
        self.index += 1
        return self.func(self.index)

This can be useful if the state you need to keep track of is more complicated (or should change in more complicated ways) than the simple integer index used in this example. It also works in Python 2 without annoying workarounds.

1
  • This answer uses best Python practices and should be the accepted answer.
    – mVChr
    Commented Nov 22, 2013 at 1:13
2

I think he wants your Make_iterator function to return a function that acts as an iterator. So you could wrap the contents of your current Make_iterator function within an inner function f and return that:

def Make_iterator(fn):
    def f():
        global x
        x+=1
        return fn(x)
    return f

Now if you do t = Make_iterator(fn), every time you call t() it will return the next value of the iterator, in your case 0, 2, 4, 6, 8, etc...

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.