如何實現迭代物件和迭代器物件?
阿新 • • 發佈:2020-11-02
程式碼:
>>> from collections import Iterator,Iterable >>> >>> >>> from collections import Iterator,Iterable >>> l = [1,2,3,4,5] >>> for x in l: ... print(x) ... 1 2 3 4 5 >>> isinstance(l,Iterable) True >>> issubclass(list,Iterable) # 判斷List是否是iterable的子類 True >>> issubclass(str,Iterable) True >>> issubclass(dict,Iterable) True >>> issubclass(int,Iterable) False >>> iter(l) # 由可迭代物件生成一個迭代器物件 <list_iterator at 0x7f7947313d68> >>> l.__iter__() # iter實際呼叫的是__iter__()方法 <list_iterator at 0x7f7946d8e668> >>> Iterable.__abstractmethods__ # 實際呼叫的是抽象基類的抽象方法 frozenset({'__iter__'}) >>> it = iter(l) >>> next(it) # 迭代器物件的next方法 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) 4 >>> next(it) 5 >>> next(it) --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-131-bc1ab118995a> in <module> ----> 1 next(it) StopIteration: >>> it.__next__() # 實際呼叫的是迭代器物件的__next__()方法 --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-132-74e64ed6c80d> in <module> ----> 1 it.__next__() StopIteration: >>> it = iter(l) >>> next(it) 1 >>> next(it) 2 >>> list(it) # 迭代器物件是一次性消費的 [3, 4, 5] >>> list(it) [] >>> it = iter(l) >>> list(it) [1, 2, 3, 4, 5] >>> it = iter(l) >>> it2 = iter(l) >>> next(it) 1 >>> next(it) 2 >>> next(it2) # 兩個迭代器物件消費各不干擾 1 >>> it = iter(l) >>> for x in it: # 迭代器本身也是可以迭代的,它也是可迭代物件 ... print(x) ... 1 2 3 4 5 >>> isinstance(it,Iterable) True >>> isinstance(it,Iterator) True >>> it.__iter__() <list_iterator at 0x7f7946deb2e8> >>> it.__iter__() is it # 迭代器物件的__iter__()方法返回的是自身 True >>>