Python implementation iterator (iterator) method example, pythoniterator

Source: Internet
Author: User

Python implementation iterator (iterator) method example, pythoniterator

Overview

An iterator is a way to access collection elements. The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only move forward without moving back.

Lazy evaluation)

The iterator does not require you to prepare all elements in the entire iteration process in advance. This element is calculated only when it is iterated to an element. Before or after this, the element may not exist or be destroyed. This feature makes it especially suitable for Traversing large or infinite sets.

Today, an entity class is created, which is roughly as follows:

Class Account (): def _ init _ (self, account_name, account_type, account_cost, return_amount = 0): self. account_name = account_name # account name self. account_type = account_type # Account type self. account_cost = account_cost # monthly settlement self. return_amount = return_amount # return amount

Create an Object List:

Accounts = [Account ("Zhang San", "yearly user", 450.00, 50), Account ("Li Si", "Monthly user", 100.00 ), account ("Yang does not regret", "Monthly end user", 190.00, 25), Account ("Let our bank", "Monthly end user", 70.00, 10 ), account ("Ling Weifeng", "yearly user", 400.00, 40)]

I want to executenext()Function, that is, click "next" when necessary to obtain the next element in the List.

Test it directly:

The List is not supported.next()Features. At this time, List is only an iterable, not an iterator.

The differences between iterable and iterator are as follows:

  1. Iterable -- only implement the _ iter _ object;
  2. Iterator -- implements both the _ iter _ and _ next _ methods.

Where,__iter__Returns the iterator object,__next__Returns the next element of the iteration process.

1. Make the list iterator

To make the previous accounts List an iterator, you only neediter()Function:

accounts_iterator = iter(accounts)(next(accounts_iterator)).account_name

The result is shown in:

It is estimated that many Python developers do not know such a simple function?

2. Custom iterator object

How to define your own iterator objects? In fact, according to the above definition__iter__And__next__Method.

Next we will define an AccountIterator class:

Class AccountIterator (): def _ init _ (self, accounts): self. accounts = accounts # account set self. index = 0 def _ iter _ (self): return self def _ next _ (self): if self. index> = len (self. accounts): raise StopIteration ("to the beginning... ") else: self. index + = 1 return self. accounts [self. index-1]

The running result is as follows:

After a while, the next () function is implemented. Python has many unexpected functions and is still waiting for us to explore. Maybe this is the charm and geeks of Python.

Summary

The above is all about this article. I hope this article will help you learn or use python. If you have any questions, please leave a message.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.