Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use iterators, generators and decorators in python

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report