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 python customizes iterators

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces python how to customize the iterator, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Custom iterator

Custom iterators are a very powerful but confusing topic for new and experienced Python developers.

Many built-in types, such as lists, collections, and dictionaries, have implemented protocols that allow them to iterate at the underlying level. This allows us to traverse them easily.

> for food in ['Pizza',' Fries']: print (food +'. Yumqi') Pizza. Yum!Fries. Yum!

How do we iterate over our own custom classes? First of all, let's clarify some terminology.

To be an iterable object, a class needs to implement _ _ iter__ ()

The _ _ iter__ () method needs to return an iterator

To be an iterator, a class needs to implement _ _ next__ () (or next () in Python 2), and a StopIteration exception must be thrown when there are no more items to iterate over.

Whoo-hoo! It sounds complicated, but once you remember these basic concepts, you can iterate at any time.

When do we want to use custom iterators? Let's imagine a scenario where we have an instance of Server running different services, such as http and ssh, on different ports. Some of these services are in the active state, while others are in the inactive state.

Class Server: services = [{'active': False,' protocol': 'ftp',' port': 21}, {'active': True,' protocol': 'ssh',' port': 22}, {'active': True,' protocol': 'http',' port': 80},]

When we traverse the Server instance, we only want to traverse the services that are in active. Let's create an IterableServer class:

Class IterableServer: def _ _ init__ (self): self.current_pos = 0 def _ next__ (self): pass # TODO: implement and remember to throw StopIteration

First, we initialize the current position to 0. Then, we define a _ _ next__ () method to return the next item. We will also make sure that StopIteration is thrown when no more items are returned. So far so good! Now, let's implement this _ _ next__ () method.

Class IterableServer: def _ init__ (self): self.current_pos = 0. # We initialize the current location to 0 def _ _ iter__ (self): # We can return self here because _ _ next__ return self def _ _ next__ (self): while self.current_pos is implemented

< len(self.services): service = self.services[self.current_pos] self.current_pos += 1 if service['active']: return service['protocol'], service['port'] raise StopIteration next = __next__ # 可选的 Python2 兼容性 我们对列表中的服务进行遍历,而当前的位置小于服务的个数,但只有在服务处于活动状态时才返回。一旦我们遍历完服务,就会抛出一个 StopIteration 异常。 因为我们实现了 __next__() 方法,当它耗尽时,它会抛出 StopIteration。我们可以从 __iter__() 返回 self,因为 IterableServer 类遵循 iterable 协议。 现在我们可以遍历一个 IterableServer 实例,这将允许我们查看每个处于活动的服务,如下所示: >

> > for protocol, port in IterableServer (): print ('service% s is running on port% d'% (protocol, port)) service ssh is running on port 22 service http is running on port 21

Great, but we can do better! In an example like this, our iterator does not need to maintain a lot of state, we can simplify the code and use generator (generator) instead.

Class Server: services = [{'active': False,' protocol': 'ftp',' port': 21}, {'active': True,' protocol': 'ssh',' port': 22}, {'active': True,' protocol': 'http',' port': 21} ] def _ _ iter__ (self): for service in self.services: if service ['active']: yield service [' protocol'], service ['port']

What exactly is the yield keyword? Use yield when defining generator functions. This is a bit like return, where return exits the function after returning a value, but yield pauses execution until the next time it is called. This allows the functionality of your generator to remain in state until it is restored. Check yield's documentation for more information. With the generator, we don't have to maintain the state manually by remembering our location. The generator only knows two things: what it needs to do now and what it needs to do for the next project. Once we reach the execution point, that is, yield is no longer called, we know to stop iterating.

This is because of some built-in Python magic. As we can see in the Python documentation on _ _ iter__ (), if _ _ iter__ () is implemented as a generator, it automatically returns an iterator object that provides the _ _ iter__ () and _ _ next__ () methods. Read this great article to learn more about iterators, iterable objects, and generators.

Thank you for reading this article carefully. I hope the article "how to customize iterators in python" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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