Refer to official Documentation:
1 Iterable is an object that can return its members . Includes sequence types (list,str,tuple) and not-sequence types (dict, file objects), objects and classed defined with an __iter__ ( ) method or a __getitem__ () method
When a Iterable object is passed into the ITER () method (also called the __iter__ () method), a iteratoris returned. This is the method of explicitly creating iterator. When we use for traversal, iterator automatically creates iterator
2 iterator should define a __iter__ () method (or a generator for iteration), because this method is iterable, iterator are iterable
The __iter__ () method of iterator returns the iterator object itself
Why are iterator all iterable? Because iterator (such as list) can be iterated (imagine concurrency), it is necessary to return a separate iterator each time __iter__ ().
If iterator is not iterable, then each call will return only the same iterator, and once the iterator reaches the stopiteration condition, it will be done.
Note: When using for traversal of an object, if the object is not __iter__, but implements the __getitem__, it uses the subscript iteration method
The same is true for ITER, when the __iter__ method is not available, it returns an iterative object with subscript iterations instead, such as Str
You can use an example to explain all of this:
classB (object):def __init__(self):Pass
defNext (self):yield 'In B next'classA (object):def __init__(self): self.b=B ()defNext (self):Print 'In A next' def __iter__(self):returnself.ba=A () forA_nextinchA: # when iterating, A_next points to B.next. forA_next_valueinchA_next: # using for traversal generator B.next, because B.next is stateless, you can always die cyclic yieldPrintA_next_value
You can rewrite the contents of the B.next to return ' in B Next ', change the a.__iter__ to yield ' in a iter ', return ' in a iter ', or even define a generator function in B to return in a.__iter__ to see the effect
Iterable and iterator in Python