How to use iterators, generators and decorators in python
This article mainly explains the "iterator in python, generator and decorator how to use", the article explains the content is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in-depth, together to study and learn "python iterator, generator and decorator how to use" it!
Iterator
Inside each iterable class, the _ _ iter__ () method is implemented, which returns an iterative class object, which defines how the iterable class iterates.
The for loop invokes list essentially by calling list's iterator for iteration.
# the for loop on list is essentially a call to the iterator list of list = [1 for 2, 3, 4] # for loop calls for elem in list: print (elem) # iterator calls list_iter = list.__iter__ () while True: try: print (next (list_iter)) except StopIteration: break
Implement a self-defined iteration class that specifies a "countdown" mode to iterate over an iterable data structure.
# iterative object class class CountDown (object): def _ _ init__ (self,num): self.num = num def _ iter__ (self): return MyIterator (self.num) # iterative class class MyIterator (object): def _ init__ (self) Num): self.NUM= num self.FINAL = 0 self.now = num def _ _ iter__ (self): return self def _ _ next__ (self): step = 1 if self.NUM