python - 为什么 'in' 关键字声称它需要一个可迭代对象?

标签 python

>>> non_iterable = 1
>>> 5 in non_iterable
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'int' object is not iterable

>>> class also_non_iterable:
...     def __contains__(self,thing):
...         return True

>>> 5 in also_non_iterable()
True
>>> isinstance(also_non_iterable(), Iterable)
False

in 关键字真正需要的是一个实现了 __contains__ 的对象时,是否有理由声称需要一个可迭代对象?

最佳答案

它声称需要一个可迭代对象,因为如果对象的类没有实现 __contains__ ,那么 in 会尝试遍历对象并检查值是否相等到它产生的值(value)。

一个例子来说明-

>>> class C:
...     def __iter__(self):
...         return iter([1,2,3,4])
>>>
>>> c = C()
>>> 2 in c
True
>>> 5 in c
False

这在 the documentation - 中有解释

For user-defined classes which define the __contains__() method, x in y is true if and only if y.__contains__(x) is true.

For user-defined classes which do not define __contains__() but do define __iter__() , x in y is true if some value z with x == z is produced while iterating over y . If an exception is raised during the iteration, it is as if in raised that exception.

关于python - 为什么 'in' 关键字声称它需要一个可迭代对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33326150/

相关文章:

python - ckan.plugins.core.PluginNotFoundException : pages

python - 如何将 Pandas 时间序列转换为带有字符串键的字典

python - scipy.sparse.csr_matrix 的最大值

python - 使用正则表达式在 Python 中获取两个字符串之间的 channel

python - 如何在opencv中正确使用peopledetect.py?

python - 在计算集群上训练 RandomForest 很慢

python - 读取 csv 文件时删除前导零

Python 四舍五入到最接近的 0.25

python - 我们可以使用 DataContentAdapter 在 plone 表单生成中搜索增值

python - 从脚本运行的 Scrapy 不起作用