Junior — Middle
99
Kad tieši kurā brīdī tiek aktivizēta metode __iter__ iterējot pa objektu?
Atbilde no AI
sobes.tech AI
Python __iter__ metode tiek izsaukts tad, kad sākas iterācija pār objektu, piemēram, izmantojot for ciklu. Konkrēti, kad interpretētājs sastop konstrukciju for element in obj:, tas izsauc obj.__iter__() lai iegūtu iteratoru.
Šis iterators ir jāievieš ar metodi __next__, kas atgriež nākamo elementu secībā. Iterācija turpinās līdz brīdim, kad __next__ izsauc izņēmumu StopIteration.
Piemērs:
class MyRange:
def __init__(self, n):
self.n = n
def __iter__(self):
self.current = 0
return self
def __next__(self):
if self.current < self.n:
val = self.current
self.current += 1
return val
else:
raise StopIteration
for i in MyRange(3):
print(i)
Šeit, ieejot ciklā, tiek izsaukts MyRange(3).__iter__(), kas atgriež iteratora objektu (šajā gadījumā, to pašu objektu), un tad tiek izsaukts __next__, lai iegūtu elementus.