开发者

Why don't python strings have an __iter__ method?

开发者 https://www.devze.com 2023-02-13 03:03 出处:网络
How is it that we can iterate over python strings when strings don\'t provide an __iter__ method? $ python

How is it that we can iterate over python strings when strings don't provide an __iter__ method?

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "asdf".__iter__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__iter__'
>>> it = iter("asdf")      
>>> it
<iterator object at 0xb736f5ac>
>>> 

My understanding from the documentation is that an __iter__ method is requi开发者_运维问答red for iteration. Why don't Python strings follow the same convention, and how do they provide iteration without doing so?


From your link:

or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0).

In [1]: 'foo'.__getitem__(0)
Out[1]: 'f'


Probably because Python isn't a langage that has a "char" type. The natural thing to return, if string did have __iter__ would be chars, but there are no chars. I can see a case for hooking __iter__ up to string and doing whatever list(someString) does, not really sure why it's not that way.

0

精彩评论

暂无评论...
验证码 换一张
取 消