Py学习  »  Python

如果没有正常函数的sentinel值,Python iter函数将无法工作

Harsh Sharma • 4 年前 • 558 次点击  

这里我定义了一个正常函数:

def abc():
  return 1

for i in iter(abc):
  print i

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object is not iterable

但现在当我用哨兵的时候,它起作用了。

 for i in iter(abc, ''):
  print i

1
1
1
1
1
1
...

你知道为什么会发生上述行为吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52913
 
558 次点击  
文章 [ 2 ]  |  最新文章 4 年前
William Bright
Reply   •   1 楼
William Bright    5 年前
Docstring:
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator

Get an iterator from an object.  In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.

所以你选择了第二种形式,这意味着它将永远循环,直到哨兵在这种情况下 '' 被退回。

snakecharmerb
Reply   •   2 楼
snakecharmerb    5 年前

iter(spam) 期望 spam

iter(spam, sentinel) 期望 垃圾邮件 iter 将调用 垃圾邮件