python custom Iterator object

from collections.abc Import Iterator 

class Company (Object):
     DEF  __init__ (Self, employee_list): 
        self.employee = employee_list 

    DEF  __iter__ (Self):
         return MyIterator (self.employee) # The list Iterator passed to the inside custom inside, and realized __iter__, then the object can be Iterator object 

class MyIterator (Iterator):
     DEF  __init__ (Self, employee_list): 
        self.iter_list = employee_list 
        self.index = 0 

    DEF  __next__ (Self):
         #Returns an iterator real value of logic 
        the try : 
            Word = self.iter_list [self.index]
         the except IndexError:
             The raise StopIteration # here must throw StopIteration, or will have been run 
        self.index + = 1 return Word IF __name__ == " __main__ " : 
    Company = Company ([ " Tom " , " Bob " , " Jane " ]) for Item in Company:
         Print (Item)
        

 

    

 

Guess you like

Origin www.cnblogs.com/callyblog/p/11080021.html