Skip to main content

Posts

user-defined class to support iteration in Python

 Two examples of iteration support in a user-defined class in Python. Example 1. The container class is used with for..in statement: class Experiment: def __init__(self): self .q = [ 1 , 2 , 3 , 4 , 5 ] self .lent = len( self .q) self .inn = 0 def __iter__(self): return self def __next__(self): if self .inn == self .lent: raise StopIteration x = self .q[ self .inn] self .inn += 1 return x ob = Experiment() for ind in ob: print(ind) run it and get: 1 2 3 4 5 Example 2. Iterator defined in the class is used with for..in statement: class Experiment: def __init__(self): self .q = [ 1 , 2 , 3 , 4 , 5 ] self .lent = len( self .q) self .inn = 0 def __iter__(self): return self def __next__(self): if self .inn == self .lent: raise StopIteration x = self .q[ self .inn] ...
Recent posts

generator in python, simple example

 How to use generators in Python?  Look at this example, pay attention to the yield statement: class Experiment: def __init__(self): self .q = [ 1 , 2 , 3 , 4 , 5 ] self .lent = len( self .q) def func_uses_generator(self): for tt in range( 0 , self .lent): x = self .q[tt] yield x ob = Experiment() for ind in ob.func_uses_generator(): print(ind) output 1 2 3 4 5