I was curious about using static variables in python, and ended up at: Why doesn't Python have static variables?
In the accepted answer, which I found informative, it is said “If you want your function’s behavior to change each time it’s called, what you need is a generator”.
However I was a bit confused, since the example used there can be done with a class as well:
class Foo(object):
def __init__(self, bar):
self.bar = bar
def __call__(self):
self.bar = self.bar * 3 % 5
return self.bar
foo = Foo(bar)
print foo()
print foo()
This makes more sense to me (but probably only because I haven’t used generators properly before).
So my question is whether there is some other advantage to using generators over classes when the function needs to change behavior each time it’s called.
Generators (the simple ones, not getting into coroutines) have a single, very specific purpose: Writing iterators. To this end, you get implicit capture of local variable and a keyword to suspend (as opposed to “terminate” – you can resume) execution and give the caller the next value of the iterator. The advantages are:
yield xwithresults.append(x)andreturn resultsat the end and get a function that’s equivalent tolist(the_original_generator(...)).self– less to type and less to read.You can use the “capture of local variable” thing to implement an iterable which behaves as, except that you can have multiple ones and you don’t invoke a function but use an iterator (
next_val = next(vals)instead ofnext_val = vals()). Whether it is appropriate depends.