1

I have got the following class:

class RandomNumbers:
    def __init__(self, length, *, range_min=0, range_max=10):
        self.length = length
        self.range_min = range_min
        self.range_max = range_max
        self.i = 0

    def __len__(self):
        return self.length

    def __next__(self):
        if self.i >= self.length:
            raise StopIteration
        number = random.randint(self.range_min, self.range_max)
        self.i += 1
        return number

    def __iter__(self):
        print("I was called")
        return self

This allows me to use a for-loop:

for number in RandomNumbers(10):
    print(number)

This works. When I comment out __iter__, I get the following error:

TypeError: 'RandomNumbers' object is not iterable

Ok, so far so good. I understand that I need the __iter__ method, but why is it needed when it actually only returns self?

1 Answer 1

3

Your for loop could be rewritten as this somewhat equivalent code

it = iter(RandomNumbers(10))
while True:
    try:
        number = next(it)
    except StopIteration:
        break
    else:
        # Body of the for loop
        print(number)

Your class needs to implement the __iter__ method to respond to the iter() function with an iterator, in your case self since your class implements __next__ making it an iterator

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.