Build a Basic Python Iterator

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

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

10条回答
  •  萌比男神i
    2020-11-21 12:49

    All answers on this page are really great for a complex object. But for those containing builtin iterable types as attributes, like str, list, set or dict, or any implementation of collections.Iterable, you can omit certain things in your class.

    class Test(object):
        def __init__(self, string):
            self.string = string
    
        def __iter__(self):
            # since your string is already iterable
            return (ch for ch in self.string)
            # or simply
            return self.string.__iter__()
            # also
            return iter(self.string)
    

    It can be used like:

    for x in Test("abcde"):
        print(x)
    
    # prints
    # a
    # b
    # c
    # d
    # e
    

提交回复
热议问题