[Tutor] Trying to write a class based iterator

Manprit Singh manpritsinghece at gmail.com
Sun Oct 3 03:05:55 EDT 2021


Dear sir ,

I have written a class based iterator for integers, as given below:

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

doing this :
rev = Intiter(309, Rev=True)   Returns an iterator
for num in rev:     # applying for loop
    print(num)

prints the digits in reverse order (Due to Rev = True when calling  the
class)
9
0
3

doing this :
forward = Intiter(309, Rev=False)

for num in forward:
    print(num)

Prints the digits in right order (Due to Rev=False when calling the class)
3
0
9

So this is basically implementation of an iterator (both Forward & Rev)
based on the input given by user Rev=True or False.
Is my implementation ok ?
Need your comments

Regards
Manprit Singh


More information about the Tutor mailing list