为什么 python 字符串没有 __iter__ 函数?

why do python strings not have __iter__ function?(为什么 python 字符串没有 __iter__ 函数?)
本文介绍了为什么 python 字符串没有 __iter__ 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当字符串没有 __iter__ 函数时,我们如何迭代 python 字符串?

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

更重要的是(无论如何迭代字符串),为什么 python 字符串不遵循与其他所有内容相同的约定.特别是当 Python 文档说需要 __iter__ 函数时 http://docs.python.org/library/functions.html#iter ?

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 ?

推荐答案

来自您的链接:

或者它必须支持序列协议(__getitem__() 方法整数参数从 0 开始).

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

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

这篇关于为什么 python 字符串没有 __iter__ 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)