We often need to traverse the elements of an object. in Python, this function is implemented through an iterator. The following article describes how to implement iterator in python. For more information, see the following.
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:
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:
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.
For more information about how to implement iterator in python, see PHP!