I'm relativley new to python (not coding) and I'm playing around with iterators in the language. When we build iterators I understand how they work and how to build a custom iterator, but I don't understand why we return self
in __iter__(self)
function.
Here's an example:
class Cube_Pow:
def __init__(self, max = 0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
cube = self.n ** 3
self.n += 1
return cube
else:
raise StopIteration
If I do the following:
cubes = Cube_Pow(10)
cube_iter = iter(cubes)
print(cube_iter) #output: <__main__.Cube_Pow object at 0x1084e8cd0>
My question is shouldn't the type be some iterator (for instance list has list_iterator
). Do have to extend some other class?