Solution 1

class PrimeNumbersIterator(object):
    def __init__(self):
        self.next_number = 2

    def __iter__(self):
        return self

    def _is_prime(self, number):
        if number in (2, 3):
            return True

        if number % 2 == 0:
            return False

        for i in range(2, number):
            if number % i == 0:
                return False
        return True

    def __next__(self):
        number = self.next_number
        while not self._is_prime(number):
            number += 1

        self.next_number = number + 1
        return number

    next = __next__

Prime Numbers Iterators

We're going to increase the complexity of our iterators practice by building an Iterator that returns only Prime Numbers. Before jumping to the Iterator itself, we've made a decision about how the object should check if a number is prime. The PrimeNumbersIterator has a _is_prime(num) method that accepts a natural number and returns True or False depending if it's prime or not. Example:

obj = PrimeNumbersIterator()
obj._is_prime(3)  # True
obj._is_prime(199)  # True
obj._is_prime(20)  # False

This means that you'll be able to use the _is_prime(num) method inside your __next__ method.

Now, about that iterator. This is an example of how it should work:

iterator = iter(PrimeNumbersIterator())

next(iterator)  # 2
next(iterator)  # 3
next(iterator)  # 5
next(iterator)  # 11
next(iterator)  # 13
# ... fast forward ...
next(iterator)  # 163
next(iterator)  # 167
next(iterator)  # 173
# Etc.

Test Cases

test prime numbers - Run Test

def test_prime_numbers():
    iterator = iter(PrimeNumbersIterator())

    assert next(iterator) == 2
    assert next(iterator) == 3
    assert next(iterator) == 5
    assert next(iterator) == 7
    assert next(iterator) == 11
    assert next(iterator) == 13
    assert next(iterator) == 17
    assert next(iterator) == 19
    assert next(iterator) == 23
    assert next(iterator) == 29
    assert next(iterator) == 31
    assert next(iterator) == 37

test is prime - Run Test

def test_is_prime():
    obj = PrimeNumbersIterator()
    prime_numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
    for number in prime_numbers:
        assert obj._is_prime(number) is True, "{} should be prime".format(number)

    not_prime_numbers = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 24, 25, 26]

    for number in not_prime_numbers:
        assert obj._is_prime(number) is False, "{} should NOT be prime".format(number)
class PrimeNumbersIterator(object): def __iter__(self): pass def _is_prime(self, number): pass def __next__(self): pass next = __next__