为什么Python Iterator需要一个只返回self的iter方法? [英] Why does a Python Iterator need an iter method that simply returns self?

查看:165
本文介绍了为什么Python Iterator需要一个只返回self的iter方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解标准说它确实存在,但我试图找到其根本原因。

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 need for it?

你显然总是有权访问该对象,因为你打电话给 iter 关于那个对象,那么有什么需要呢?

You clearly always have access to the object since you are calling iter on that object, so what's the need for having it?

推荐答案

想象一下你想写代码迭代任何类型的迭代。通常你只需为语句或理解写一个,但让我们明确地做 的内容,使事情更明显:

Imagine you want to write code that iterates over any kind of iterable. Normally you'd just write a for statement or comprehension, but let's instead explicitly do what for does under the covers, to make things more obvious:

i = iter(iterable)
while True:
    try:
        val = next(i)
    except StopIteration:
        break
    else:
        do_stuff(val)

如果你不做第一行,你的代码将无法使用列表,字符串,元组或除迭代器之外的任何东西。

If you don't do that first line, your code won't work with lists, strings, tuples, or anything but iterator.

但是如果你做第一行,那么, iter(可迭代)最好返回一个迭代器,否则你的代码将无法使用迭代器。

But if you do that first line, well, iter(iterable) had better return an iterator, or your code won't work with iterators.

你可能想知道为什么 iter 不能做到没有这个正确的事情?毕竟,当给定一个具有 __ len __ __ getitem __ <的对象时,它确实可以创建一个迭代器/ code>但是没有 __ iter __ ,那么为什么如果它有一个 __ next __ 但没有 __ iter __ ?这是一个语言设计问题,但一般来说,Python试图尽可能少地使用魔法。使非完全序列可迭代的魔力是必要的,因为在迭代协议被添加到语言之前存在这种序列(在广泛的第三方代码中),并且为了简化事物的微小好处而移除它将太难。

You may wonder why iter couldn't just do the right thing without this? After all, it does have magic in it to create an iterator when given an object that has a __len__ and __getitem__ but no __iter__, so why couldn't it also have magic to just return its argument if it has a __next__ but no __iter__? That's a language-design issue, but generally, Python tries to have as little magic as possible. The magic to make not-quite-sequences iterable was necessary because such sequences existed (in widespread third-party code) before the iteration protocol was added to the language, and it would be too hard to remove for the small benefit of simplifying things.

这篇关于为什么Python Iterator需要一个只返回self的iter方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆