Python中可以存在非对象吗?

nne*_*neo 5 python object base-class

众所周知,在Python中一切都是对象。我想知道的是是否有可能创建一个“对象” x,以便isinstance(x, object)返回False. I suspect it's possible with sufficient abuse of the CPython API, though achieving this with pure Python would be even more interesting.

最初我认为旧式类会返回,False因为对象层次结构可能不完全适用,但似乎isinstance(x, object)确实True适用于旧式类的实例。

虽然这主要是理论上的兴趣,但如果 Python 允许创建与基本object类型断开连接的新对象层次结构,它可能会很有趣(或危险)。

ant*_*ony 3

当然,您可以通过 C API 完成所有操作(特别是通过 Awesomeforbiddenfruit模块)

>>> from forbiddenfruit import curse
>>> class C: pass
... 
>>> curse(type, "__instancecheck__", lambda cls, obj: type(obj) != C)
>>> isinstance(C(), object)
False
>>> isinstance(C(), C)
True
Run Code Online (Sandbox Code Playgroud)