[Python] iterator and iterable classes in python [closed]

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    [enter image description here][1]Why do we return self in the iter method when we define the next method in the iterable and iterator classes?

    This topic was taught in the course, but it was hard to understand and I didn't understand why we had to return self.

    class PowTwo:
    def __init__(self, max_pow):
    self.n = 0
    self.max_pow = max_pow

    def __iter__(self):
    return self

    def __next__(self):
    if self.n <= self.max_pow:
    result = self.n ** 2
    self.n += 1
    return result
    else:
    raise StopIteration
    n = PowTwo(5)
    for i in n:
    print(i)

    Continue reading...

Compartilhe esta Página