python中的iter函数

  • Post author:
  • Post category:python


1,iter(object)

例子:

lst = [1, 2, 3]

for i in iter(lst):

print(i)

2,iter(object, sentinel)

例子:

class counter:

    def __init__(self, _start, _end):
        self.start = _start
        self.end = _end

    def get_next(self):
        s = self.start
        if(self.start < self.end):
            self.start += 1
            print('----------',self.start)
            print('++++++++++',self.end)
        else:
            print(self.start)
            print(self.end)
            raise StopIteration

        return s


c = counter(1, 4)
iterator = iter(c.get_next, 5)#当返回值为5时抛出异常
print(type(iterator))
for i in iterator:
    print('===================================',i)

运行结果如下:

C:\Users\snowshuang\AppData\Local\Programs\Python\Python37\python.exe C:/Users/snowshuang/PycharmProjects/logging/log1.py

<class ‘callable_iterator’>

———- 2

++++++++++ 4

=================================== 1

———- 3

++++++++++ 4

=================================== 2

———- 4

++++++++++ 4

=================================== 3

4

4