>>> 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 ify.__contains__(x)
is true.For user-defined classes which do not define
__contains__()
but do define__iter__()
,x in y
is true if some valuez
withx == z
is produced while iterating overy
. 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/