, , , ( , ...)
A Python . , :
for element in iterable:
foo(element)
:
iterator = iterable.__iter__()
try:
while True:
element = iterator.next()
foo(element)
except StopIteration:
pass
, , next, ( , StopIteration).
Thus, each iterative object from which the nextiterator method never raises the mentioned exception has an infinite loop. For example:
class InfLoopIter(object):
def __iter__(self):
return self
def next(self):
return None
class InfLoop(object):
def __iter__(self):
return InfLoopIter()
for i in InfLoop():
print "Hello World!"
source
share