Python 3 about ITER (object[, Sentinel)] The method has two parameters.
This form of use of ITER (object) is more common.
The use of ITER (object, Sentinel) in this form is relatively small, and Python's documentation is seemingly not easy to understand.
Therefore, the use of this function is illustrated here.
1,iter (object)
The official Python documentation is easy to understand for this form of interpretation.
At this point, object must be a collection object and support an iterative protocol (iteration protocol) or a support sequence protocol (sequence protocol).
Plainly, that is, the __iter__ () method or the __getitem__ () method is implemented.
1 lst = [1, 2, 3]2 for in ITER (LST):3 Print (i)
Execution Result:
1
2
3
2,iter (object, Sentinel)
The official Python documentation for this form is interpreted as: "If the second argument, Sentinel, is given, then object must be a callable object . The iterator created in this case would call object with no arguments for each call to its __next__() method; if the VA Lue returned is equal to Sentinel, would be StopIteration raised, otherwise the value would be returned. "
If you pass the second argument, object must be a callable object (for example, a function). At this point, ITER creates an iterator object that is invoked each time the __next__ () method of the iterator object is called.
If the return value of __next__ equals Sentinel, the Stopiteration exception is thrown, otherwise the next value is returned.
1 classCounter:2 3 def __init__(self, _start, _end):4Self.start =_start5Self.end =_end6 7 defGet_next (self):8s =Self.start9 if(Self.start <self.end):TenSelf.start + = 1 One Else: A Raisestopiteration - - returns the - -c = Counter (1, 5) -iterator = iter (C.get_next, 3) + Print(Type (iterator)) - forIinchiterator: + Print(i)
Execution Result:
<class ' Callable_iterator ' >
1
2
Instructions for using the Python ITER method