2015-11-02 23 views
0

我看了一下建在从Python文档对象的迭代方法:为什么Python可迭代对象按照他们的方式工作?

https://docs.python.org/2/library/stdtypes.html#iterator-types

是怎么说__iter__方法如下:

Return an iterator object. The object is required to support the iterator protocol described below.

然而,在我看来,这似乎不是这种情况,如果我使__iter__方法返回一个字符串,如'abc'我得到一个类型错误:TypeError: iter() returned non-iterator of type 'str'但我们知道,字符串是可迭代的对象,它怎么可能像Python那样对待它是n一个迭代对象?

我可以解决这样这个问题:

def __iter__(self): 
    return 'abc'.__iter__() 

,但我不明白为什么我必须这样做,这样,而不是仅仅返回'abc'对象。

我还注意到Python文档对初学者不是很有帮助,它确实没有让这个学习过程变得简单。用什么逻辑可以得出结论return 'abc'.__iter__()是通过阅读文档去的路?

如果您对我在哪里可以深入了解更多关于内置方法等方面的任何建议,如果您愿意分享,我会非常高兴。

+3

字符串是*迭代*,但他们不是*迭代器*。该文档完全清楚构成* iterator *的是什么:支持迭代器协议的任何对象。 – nneonneo

回答

1

务实的答案:迭代器需要支持next()

的字符串不会:

next('abc') 
TypeError: 'str' object is not an iterator 

只是要迭代是不够的。

+0

我看,似乎我认为字符串有'__next__'方法,因为您可以迭代它。这似乎是迄今为止最好的答案。 – Parsee

+0

内置序列都不是迭代器。他们都有一个相应的迭代器。 'iter('abc')'返回'。这种分离不仅可以重新迭代,而且可以同时拥有多个迭代器。考虑s ='abc'\ nfor c1 in s:\ n for c2 in s:\ n yield c1,c2' to get all ordered ordered pairs of letters in s s each for for循环调用iter(s)来获得它自己的迭代器。 –

1

这有点一个细点,但关键是一个迭代(例如,iter("abc")或等效"abc".__iter__())和迭代(例如,​​)是两个略微不同的东西,__iter__需要返回一个迭代。

1

字符串是一个可以迭代的对象,但它本身不是迭代器。它们是对象层次结构中的两个独立的类。

0

从Python Documentation

可迭代是

an object capable of returning its members one at a time.

This means all sequence types (list , str , and tuple objects) and some non-sequence types like dict and file and objects of any classes you define with an __iter__() or __getitem__() methoda are iterables.

Iterables can be used in a for loop and in many other places where a sequence is needed (zip() , map() , ...). When an iterable object is passed as an argument to the built-in function iter() , it returns an iterator for the object.

在另一方面迭代器是

an object representing a stream of data.

Repeated calls to the iterator’s next() method return successive items in the stream. When no more data are available a StopIteration exception is raised instead.

相关问题