In: Computer Science
Describe the characteristics of situations when generators are a good solution? python
`Hey,
Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.
On one level, you can think of a Python generator as (among other things) a readable shortcut for creating iterators. Here's gen_nums again:
def gen_nums(): n = 0 while n < 4: yield n n += 1
If you couldn't use "yield," how would you make an equivalent iterator? Just define a class like this:
class Nums: MAX = 4 def __init__(self): self.current = 0 def __iter__(self): return self def __next__(self): next_value = self.current if next_value >= self.MAX: raise StopIteration self.current += 1 return next_value
Yikes. An instance of this works just like the generator object above…
nums = Nums() for num in nums: print(num) >>> nums = Nums() >>> for num in nums: ... print(num) 0 1 2 3
…but what a price we paid. Look at how complex that class is, compared to the gen_nums function. Which of these two is easier to read? Which is easier to modify without screwing up your code? Which has the key logic all in one place? For me, the generator is immensely preferable.
And it illustrates the encapsulation. It provides new and useful ways for you to package and isolate internal code dependencies. You can do the same thing with classes, but only by spreading state across several methods, in a way that's not nearly as easy to understand.
Kindly revert for any queries
Thanks.