[Tutor] Trying to write a class based iterator

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 3 04:22:43 EDT 2021


On 03/10/2021 08:05, Manprit Singh wrote:

> class Intiter:
>     """Iterator for looping over digits of integer"""
>     def __init__(self, data, Rev):
>         self.data = data if Rev else int(str(data)[::-1])
> 
>     def __iter__(self):
>         return self
> 
>     def __next__(self):
>         if self.data == 0:
>             raise StopIteration
>         self.data, rem = divmod(self.data, 10)
>         return rem

> Is my implementation ok ?
> Need your comments

Its OK but it might be simpler to just store the number
as a string and return the characters. That would remove
the need for one of the conversions in the init() as well
as the divmod calculation.

Of course if the user wanted to use the numbers they would
need to convert to int() later.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list