Python 3中關於iter(object[, sentinel)]方法有兩個參數。
使用iter(object)這種形式比較常見。
iter(object, sentinel)這種形式一般較少使用,Python的文檔說明貌似也不容易理解。
故,在此舉例說明一下此函數的用法。
1,iter(object)
Python官方文檔對於這種形式的解釋很容易理解。
此時,object必須是集合對象,且支持迭代協議(iteration protocol)或者支持序列協議(sequence protocol)。
說白了,也就是實現了__iter__()方法或者__getitem__()方法。
1 lst = [1, 2, 3] 2 for i in iter(lst): 3 print(i)
執行結果:
1
2
3
2,iter(object, sentinel)
Python官方文檔對於這種形式的解釋是:“ If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__()
method; if the value returned is equal to sentinel,StopIteration
will be raised, otherwise the value will be returned.”。
這句話的意思是說:如果傳遞了第二個參數,則object必須是一個可調用的對象(如,函數)。此時,iter創建了一個迭代器對象,每次調用這個迭代器對象的__next__()方法時,都會調用object。
如果__next__的返回值等於sentinel,則拋出StopIteration異常,否則返回下一個值。
1 class counter: 2
3 def __init__(self, _start, _end): 4 self.start = _start 5 self.end = _end 6
7 def get_next(self): 8 s = self.start 9 if(self.start < self.end): 10 self.start += 1
11 else: 12 raise StopIteration 13
14 return s 15
16
17 c = counter(1, 5) 18 iterator = iter(c.get_next, 3) 19 print(type(iterator)) 20 for i in iterator: 21 print(i)
執行結果:
<class 'callable_iterator'>
1
2