Why does a Python Iterator need an iter method that simply returns self?

后端 未结 4 841
面向向阳花
面向向阳花 2021-01-06 05:35

I understand that the standard says that it does but I am trying to find the underlying reason for this.

If it simply always returns self what is the ne

4条回答
  •  悲&欢浪女
    2021-01-06 06:15

    for loops should work with iterables, so for i in something: automatically calls iter(something) to get an iterator and iterates over said iterator. Now if iterators weren't iterable too (i.e. did not define __iter__), you couldn't use for loops with iterators, i.e.:

    items = [1, 2, 3]
    # this would work
    for item in items: pass
    # this wouldn't
    it = iter(items)
    for item in it: pass
    

    Therefore, iterators should be iterables too. The alternative, "somehow detecting" iterators and not calling iter on them, is hacky and fragile (how would you decide that?).

提交回复
热议问题