- execute __getitem __ () method with integer arguments starting at 0.
Custom object does not deploy __iter __ (), __next () or __getitem __ () None Exception ExceptionTypeError
exception Callable object Provided Function returns an iterator object that can call an object There is no argument for each call to its __next __ () method, if Sentinel is found, the exception StopIteration
exception will be generated. The iter () function returns an iterator object for the parameter to be passed , which can iterate through each of its elements at a given time.
In case the second parameter sentinel is passed, the function that returns the iterator object can call the callable object until no sentinel character is found.
# danh sach nguyen am # viet boi TipsMake.com nguyenam = ['a', 'e', 'i', 'o', 'u'] nguyenamIter = iter(nguyenam) # in ra 'a' print(next(nguyenamIter)) # in ra 'e' print(next(nguyenamIter)) # in ra 'i' print(next(nguyenamIter)) # in ra 'o' print(next(nguyenamIter)) # in ra 'u' print(next(nguyenamIter))
When you run the program, the output output will be:
aeiou
class PrintNumber: def __init__(self, max): self.max = max def __iter__(self): self.num = 0 return self def __next__(self): if(self.num >= self.max): raise StopIteration self.num += 1 return self.num printNum = PrintNumber(3) printNumIter = iter(printNum) # in ra '1' print(next(printNumIter)) # in ra '2' print(next(printNumIter)) # in ra '3' print(next(printNumIter)) # sinh ra StopIteration print(next(printNumIter))
Run the program, the result is:
1 2 3 StopIteration
with open('mydata.txt') as fp: for line in iter(fp.readline, ''): processLine(line)
When you run the program, Python will open mydata.txt in read mode.
Then iter(fp.readline, '')
in the for loop calls readline (read each line in the text file) until the sentinel character ''
(empty string) is found.
See also: Built-in Python functions