from collections import Iterable, Iterator
html
參考官網連接python
class I: def __init__(self, v): self.v = v def __iter__(self): return iter([self.v]) # 返回的應該是迭代器對象 i = I(2) print(isinstance(i, Iterable), isinstance(i, Iterator)) # True False print(iter(i)) # <list_iterator object at 0x00000000021C8358> class I: def __init__(self, v): self.v = v def __getitem__(self, item): if item > self.v: raise IndexError return item i = I(2) print(isinstance(i, Iterable), isinstance(i, Iterator)) # False False print(iter(i)) # <iterator object at 0x0000000001DFCD30>
參考官網連接ide
class I: def __init__(self, v): self.v = v def __iter__(self): return self def __next__(self): if self.v < 10: self.v += 1 return self.v raise StopIteration i = I(2) print(isinstance(i, Iterable), isinstance(i, Iterator)) # True True print(iter(i)) # <__main__.I object at 0x00000000021E0898>
參考官網連接函數
class I: def __init__(self, v): self.v = v def __iter__(self): yield 1 i = I(2) print(isinstance(i, Iterable), isinstance(i, Iterator)) # True False print(iter(i)) # <generator object I.__iter__ at 0x00000000022204C0>