Python 为什么不总是根据参数调用_instancecheck __?
有以下代码:Python 为什么不总是根据参数调用_instancecheck __?,python,python-3.x,Python,Python 3.x,有以下代码: class Meta(type): def __instancecheck__(self, instance): print("__instancecheck__") return True class A(metaclass=Meta): pass a = A() isinstance(a, A) # __instancecheck__ not called isinstance([], A) # __instancecheck__ called
class Meta(type):
def __instancecheck__(self, instance):
print("__instancecheck__")
return True
class A(metaclass=Meta):
pass
a = A()
isinstance(a, A) # __instancecheck__ not called
isinstance([], A) # __instancecheck__ called
为什么对
[]
参数调用\uu实例检查
,而不是对参数调用\uu实例检查?PyObject\u实例
对精确匹配进行快速测试
:
不喜欢快车道吗?您可以尝试以下方法(风险自负):
我认为描述\uuuu instancecheck\uuuu()
的PEP是错误的。政治公众人物3119说:
这里提出的主要机制是允许重载
内置函数isinstance()和issubclass()。超载
工作原理如下:调用isinstance(x,C)首先检查
C.\uuuu instancecheck\uuuu
存在,如果存在,则调用C.\uuuu instancecheck\uuux)
而不是它的正常实现
你可以写:
class C:
def do_stuff(self):
print('hello')
C.do_stuff(C())
因此,根据上述政治公众人物的引述,你应该能够
class C:
@classmethod
def __instancecheck__(cls, x):
print('hello')
C.__instancecheck__(C())
--output:--
hello
但isinstance()不调用该方法:
class C:
@classmethod
def __instancecheck__(cls, y):
print('hello')
x = C()
isinstance(x, C)
--output:--
<nothing>
isinstance(x, C)
--output:--
<nothing>
但isinstance()再次不调用该方法:
class C:
@classmethod
def __instancecheck__(cls, y):
print('hello')
x = C()
isinstance(x, C)
--output:--
<nothing>
isinstance(x, C)
--output:--
<nothing>
isinstance(x,C)
--输出:--
结论:PEP 3119需要与“数据模型”文档一起重写。这与以下内容有关(但不是重复内容):
isinstance(x, C)
--output:--
<nothing>