【发布时间】:2019-03-12 06:55:45
【问题描述】:
# python3.7
Python 3.7.2 (default, Feb 15 2019, 16:54:46)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections.abc import *
>>> from _collections_abc import _check_methods
>>> class A:
... pass
...
>>> a = A()
>>> isinstance(a, Iterable)
False
>>> A.__iter__ = 100
>>> isinstance(a, Iterable) # why this not working?
False
>>> _check_methods(A, "__iter__")
True
>>> class B:
... def __iter__(self):
... pass
...
>>> isinstance(B(), Iterable)
True
我用__iter__ 修补了A,所以isinstance(a, Iterable) 应该返回True,因为它现在就像定义了__iter__ 的可迭代对象。从source来看,Iterable只根据类是否实现了__iter__来判断。
那么为什么这个猴子补丁没有像我预期的那样工作?
【问题讨论】:
标签: python isinstance