why do python strings not have __iter__ function?

2019-03-15 00:24发布

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

$ 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>
>>> 

And more importantly (however strings are iterated over), why do python strings not follow the same convention as everything else. Particularly when the Python docs say that the __iter__ function is needed http://docs.python.org/library/functions.html#iter ?

2条回答
放我归山
2楼-- · 2019-03-15 01:03

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.

查看更多
贼婆χ
3楼-- · 2019-03-15 01:12

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'
查看更多
登录 后发表回答