I'm a bit confused with the use of methods like __iter__()
and __next__()
(I suppose they are called dunders).
I was trying to understand iterators and iterables and wrote this code:
x = (1, 2, 3, 4, 5, 6)
try:
y = x.__iter__()
while 1:
print(y.__next__())
except StopIteration:
print('Iterator has exhausted')
Then the code got executes without error when I used __iter__
and __next__
as functions:
x = (1, 2, 3, 4, 5, 6)
try:
y = iter(x)
while 1:
print(next(y))
except StopIteration:
print('Iterator has exhausted')
Can anybody tell me how they can be used as both a method and function? And is it applicable to all dunders?