Iterable和Iterator
from collections.abc import *
c = list()
a=[1,2,3,4]
print(isinstance(a,Iterable)) # True
print(isinstance(a,Iterator)) # False
print("################")
print(isinstance(iter(a),Iterable)) # True
print(isinstance(iter(a),Iterator)) # True
Iterable: implemented in the class__iter__
iterator: implements __iter__
and at the same time in the class__next__
ps:
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
In the class:
iter call __iter__
, return the implemented __next__
object, If the current class is implemented __next__
, you can alsoreturn self
Real iterator
- iter call
__iter__
function __iter__
Return the implemented__next__
object, so we can use the next function to access the next element of this object
class MyRange(object):
def __init__(self, end):
self.start = 0
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start < self.end:
ret = self.start
self.start += 1
return ret
else:
raise StopIteration
from collections.abc import *
a = MyRange(5)
print(isinstance(a, Iterable))
print(isinstance(a, Iterator))
for i in a:
print(i)
class MyRange(object):
def __init__(self, end):
self.start = 0
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start < self.end:
ret = self.start
self.start += 1
return ret
else:
raise StopIteration
a = MyRange(5)
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a)) # 其实到这里已经完成了,我们在运行一次查看异常
Reference: https://www.jianshu.com/p/1b0686bc166d