Overview
Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.
Deferred or lazy evaluation (lazy evaluation)
Iterators do not require that you prepare all the elements in advance for the entire iteration. The element is evaluated only when it is iterated to an element, and before or after that, the element may not exist or be destroyed. This feature makes it particularly useful for traversing large or infinite collections.
An entity class was created today, 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 junction cost SEL F.return_amount = return_amount # return Amount
Then create a list of entities:
accounts = [Account ("Zhang San", "annual fee", 450.00, $), accounts ("John Doe", "Monthly User", 100.00), Account ("Yang does not Regret", "monthly Knot user", 190.00, 25) , Account ("I-Line", "Monthly User", 70.00, ten), accounts ("Ling Feng", "annual fees", 400.00, 40)]
I want to perform the function, that is, next() "next" when needed, to get the next element in the list.
Test it directly:
The results found that the list does not support next() attributes. At this point, list is just a iterable, not a iterator.
The differences between iterable and iterator are as follows:
iterable--only realizes the object of __iter__;
iterator--also implements the objects of the __iter__ and __next__ methods.
Where the __iter__ iterator object is returned, the __next__ next element of the iteration process is returned.
1. Make the list a iterator
To make the previous accounts List a iterator, just a simple iter() function:
Accounts_iterator = iter (Accounts) (Next (Accounts_iterator)). account_name
The results are as follows:
There are still a lot of python developers who don't know about this simple function.
2. Customizing iterator objects
Extension, how do you define your own iterator object? In fact, according to the above definition, implementation __iter__ and __next__ method.
We then define a Accountiterator class:
Class Accountiterator (): Def __init__ (self, accounts): self.accounts = accounts # account Set Self.index = 0 def __iter__ (self): Return self def __next__: if Self.index >= len (self.accounts): Raise Stopiteration ("head up ...") Else: Self.index + = 1 return self.accounts[self.index-1]
Running results such as:
The next () function is implemented by the
through this toss. Python has a lot of unexpected features, but also waiting for us to continue to explore, perhaps this is the charm of Python and geek.