Build a Basic Python Iterator

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

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

10条回答
  •  滥情空心
    2020-11-21 12:50

    Include the following code in your class code.

     def __iter__(self):
            for x in self.iterable:
                yield x
    

    Make sure that you replace self.iterablewith the iterable which you iterate through.

    Here's an example code

    class someClass:
        def __init__(self,list):
            self.list = list
        def __iter__(self):
            for x in self.list:
                yield x
    
    
    var = someClass([1,2,3,4,5])
    for num in var: 
        print(num) 
    

    Output

    1
    2
    3
    4
    5
    

    Note: Since strings are also iterable, they can also be used as an argument for the class

    foo = someClass("Python")
    for x in foo:
        print(x)
    

    Output

    P
    y
    t
    h
    o
    n
    

提交回复
热议问题