第一種:__iter__

實現__iter__的對象,是可迭代對象。__iter__方法可以直接封裝一個迭代器,從而實現for循環

class A:
    def __init__(self):
        self.lis = [1,2,3,4]
    def __iter__(self):
        for i in self.lis:
            yield i


a = A()
for i in a:
    print(i)

 

第二種:__iter__ 和 __next__

利用__iter__返回自己,會進一步調用__next__方法,注意__next__方法要有raise StopIteration 的終止條件

class B:
    def __init__(self):
        self.lis = [1,2,3,4]
        self.c = -1
    def __iter__(self):
        return self
    def __next__(self):
        if self.c < self.lis.__len__()-1:
            self.c+=1
            return self.lis[self.c]
        else:
            raise StopIteration  # 一定有終止

 

第三種:__getitems__

for statement的另一個機制是角標索引,所以利用__getitems__方法同樣可以實現

class C:
    def __init__(self):
        self.a = [1,2,3,4]
    def __getitem__(self, item):
        return self.a[item]


c = C()
for i in c:
    print(i)