<blockquote>
<p>Overriding the <code>__instancecheck__</code> and <code>__subclasscheck__</code> methods of <code>Base</code>. This doesn't work because CPython only calls these methods when conventional checks return <code>False</code>.</p>
</blockquote>
<p>这种说法是一种误解。这些钩子将在<em>元类</em>上定义,而不是在基类(<a href="https://docs.python.org/3/reference/datamodel.html#customizing-instance-and-subclass-checks" rel="nofollow noreferrer">docs</a>)上定义。你知道吗</p>
<pre><code>>>> class Meta(type):
... def __instancecheck__(self, instance):
... print("instancecheck", self, instance)
... return False
... def __subclasscheck__(self, subclass):
... print("subclasscheck", self, subclass)
... return False
...
>>> class Base(metaclass=Meta):
... pass
...
>>> class Derived(Base):
... pass
...
>>> obj = Derived()
>>> isinstance(obj, Base)
instancecheck <class '__main__.Base'> <__main__.Derived object at 0xcafef00d>
False
>>> issubclass(Derived, Base)
subclasscheck <class '__main__.Base'> <class '__main__.Derived'>
False
</code></pre>
<p>请注意CPython性能优化,这些优化在某些特殊情况下会阻止调用自定义实例检查挂钩(有关详细信息,请参见<a href="https://stackoverflow.com/q/47740953/674039">here</a>)。特别是,您可能无法对<code>isinstance(obj, Derived)</code>的返回值进行强arm,因为<a href="https://github.com/python/cpython/blob/v3.7.3/Objects/abstract.c#L2377-L2379" rel="nofollow noreferrer">CPython fast path</a>存在完全匹配。你知道吗</p>
<p>最后一点,我同意评论人士的看法,这听起来不是一个很有前途的设计。在这种情况下,似乎应该考虑使用组合而不是继承。你知道吗</p>