Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use iterators, generators and decorators in python

Shulou Source: shulou.com Published: 2022-06-01 14:57:55 09月28日 Update

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

Tags: Iteration function generator generation object parameter log content function file learning encapsulation loop output instruction mode essence annotation program system Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Xiaomi Shulou Technology NVidia MariaDB