[英]Does `type.__instancecheck__` implement the default behavior of `isinstance`?
The docs say the following: 文档说明如下:
[...] If defined, called to implement
isinstance(instance, class)
. [...] 如果已定义,则调用以实现isinstance(instance, class)
。
The wording suggests that it makes a difference whether __instancecheck__
is defined or not.措辞表明是否定义了__instancecheck__
会有所不同。 Ie it doesn't say "Override to implement isinstance
" where it would be clear that the base implementation ( type.__instancecheck__
) provides the default behavior.即它没有说“覆盖实现isinstance
” ,其中很明显基本实现( type.__instancecheck__
)提供了默认行为。
To be more specific I would like to know whether the following meta class results in similar behavior as if I omitted the definition of __instancecheck__
:更具体地说,我想知道以下元类是否会导致类似的行为,就像我省略了__instancecheck__
的定义__instancecheck__
:
class Meta(type):
def __instancecheck__(self, instance):
return super().__instancecheck__(instance)
class Test(metaclass=Meta):
pass
isinstance(<something>, Test)
My intuition says yes, but the wording of the docs makes me worry that isinstance
takes a different path based on whether __instancecheck__
is defined or not.我的直觉是肯定的,但是文档的措辞让我担心isinstance
会根据__instancecheck__
是否定义而采用不同的路径。 In the end I would like to know whether I can fall back to super().__instancecheck__(instance)
in my own implementation of __instancecheck__
in order to get the default behavior.最后我想知道我是否可以在我自己的__instancecheck__
实现中回退到super().__instancecheck__(instance)
以获得默认行为。
isinstance
doesn't act any different with or without __instancecheck__
being defined. __instancecheck__
是否定义了__instancecheck__
, isinstance
都没有任何不同。 Also, "falling back" on super().__instancecheck__(instance)
is unnecessary.此外,在super().__instancecheck__(instance)
上“回退”是不必要的。 According to https://bugs.python.org/issue35083 , "any object x
is always considered to be an instance of type(x)
, and this cannot be overridden."根据https://bugs.python.org/issue35083 ,“任何对象x
始终被视为type(x)
的实例,并且不能被覆盖。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.