why do python strings not have __iter__ function?

前端 未结 2 1186
一生所求
一生所求 2021-02-05 06:45

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:         


        
相关标签:
2条回答
  • 2021-02-05 07:28

    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 讨论(0)
  • 2021-02-05 07:49

    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'
    
    0 讨论(0)
提交回复
热议问题