python - Iterables/generators explanation -


can explain how __next__ works code below? know 'next' used iterators grab next item of iterable, usualy next().

i know __iter__ part gets executed because of list() call executes __next__. __next__keeps executing, while loop? until stopiteration executed?

also, 'return' elements getting stored under __next__? stored in memory until return self under __iter__ returns calling function?

class frange(object):     def __init__(self, start, stop=none, step=none):            if stop none:             self.i = 0             self.stop = start             self.step = 1         elif step none:             self.i = start             self.stop = stop             self.step = 1         else:             self.i = start             self.stop = stop             self.step = step      def __iter__(self):         return self      def __next__(self):                                      if self.i < self.stop , self.step > 0:             self.i += self.step             return self.i - self.step         elif self.i > self.stop , self.step < 0:             self.i += self.step             return self.i - self.step         else:             raise stopiteration   def rangefloat(args):     return list(frange(*args))   

the code above produces example:

for args = [-1.1, 2.4, 0.3], output rangefloat(args) = [-1.1, -0.8, -0.5, -0.2, 0.1, 0.4, 0.7, 1, 1.3, 1.6, 1.9, 2.2]. 

list works like

def list(thing):     result = []     item in thing:         result.append(item)     return result 

and for loop:

for item in thing:     # loop body 

works like

iterator = iter(thing): while true:     try:         item = next(iterator)     except stopiteration:         break     # loop body 

putting these things together, list calls frange instance's __iter__ method iterator; in case, iterator frange instance itself. calls __next__ repeatedly , appends __next__ return values list until __next__ raises stopiteration. once stopiteration raised, list returns list built.


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -