Build a Basic Python Iterator

前端 未结 10 1059
南旧
南旧 2020-11-21 12:22

How would one create an iterative function (or iterator object) in python?

10条回答
  •  天涯浪人
    2020-11-21 12:57

    If you looking for something short and simple, maybe it will be enough for you:

    class A(object):
        def __init__(self, l):
            self.data = l
    
        def __iter__(self):
            return iter(self.data)
    

    example of usage:

    In [3]: a = A([2,3,4])
    
    In [4]: [i for i in a]
    Out[4]: [2, 3, 4]
    

提交回复
热议问题