Iterable和Iterator

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

  1. iter call __iter__function
  2. __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

Guess you like

Origin blog.csdn.net/weixin_46129834/article/details/113992475