Python learning-How to implement an iterative object (itearable) and an iterator (iterator)

Source: Internet
Author: User
Tags generator generator iterable

About Object iterable and iterator objects that can be iterated iterator

An iterative object: An object that can act directly on a for loop is called an iterative object: Iterable. An iterative object contains an __iter__ method, or __getitem__ method, where the __iter__ method returns an iterator iterator.

      An iterative object is a collection of data types, such as List,tuple, Dict, Set,str, and another type of iterative object that is the generator generator.

Iterator object: An object that can be used as the next () function is an iterator object. An iterator object must implement the __next__ method.

For loop, if the loop is an iterative object iterable, it calls the Iterable __iter__ method, returns an iterator, and then calls his next method until a Stopiteration exception is encountered to jump out of the loop.

If the loop is an iterator object, call the next method directly, knowing that a stopiteration exception has been encountered to jump out of the loop.

Sir, as an iterator object, it is regenerated into an iterative object.

From collections Import iterator,iterable
class Aiterator (Iterator):
def __init__ (self, S, e):
self.current = s
self.end = e
# def __iter__ (self):
# return self
def __next__ (self):
if self.current < self.end:
Self.index = self.current
self.current + = 1
return Self.index
Else:
Raise Stopiteration
class Aiterable:
def __init__ (self,s,e):
Self.s=s
self.e=e
def __iter__ (self):
return Aiterator (SELF.S,SELF.E)

it = aiterator (1,10)
iteable=aiterable (2,5)
For i in it:
print (i)

Python learning-How to implement an iterative object (itearable) and an iterator (iterator)

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.