__instancecheck__-覆盖不起作用-我做错了什么? [英] __instancecheck__ - overwrite shows no effect - what am I doing wrong?
问题描述
我试图使我的类作为另一个对象出现,以规避我正在使用的程序包中的惰性类型检查.更具体地说,我试图使我的对象显示为另一个对象的实例(在本例中为tuple
),而实际上它甚至不是该对象的派生.
I'm trying to make my class appear as a different object to circumvent lazy type checking in a package I'm using. More specifically, I'm trying to make my object appear as an instance of another object (tuple
in my case) when in reality it is not even a derivation of that.
为了实现这一点,我计划根据
In order to achieve this, I plan to overwrite the __isinstance__
method which, according to the docs, should do exactly what I desire. However, it appears that I didn't understand how do to do that exactly, because my attempts have been unsuccessful.
这是一个SSCCE,应该应该使isinstance
在所有情况下都返回False
,但并非如此.
Here's an SSCCE that should make isinstance
return False
in all cases but doesn't.
class FalseInstance(type):
def __instancecheck__(self, instance):
return False
class Foo(metaclass=FalseInstance):
pass
g = Foo()
isinstance(g, Foo)
> True
我在做什么错了?
推荐答案
除了__metaclass__
的问题和用于精确类型匹配的快速路径之外,__instancecheck__
的作用与尝试的方向相反去做.类的__instancecheck__
检查是否将其他对象视为该类的虚拟实例,而不是将该类的实例是否视为其他类的虚拟实例.
Aside from the issues with __metaclass__
and the fast-path for an exact type match, __instancecheck__
works in the opposite direction from what you're trying to do. A class's __instancecheck__
checks whether other objects are considered virtual instances of that class, not whether instances of that class are considered virtual instances of other classes.
如果您希望对象在isinstance
检查中位于其类型附近(您实际上不应该这样做),那么执行此操作的方法是在__class__
附近,而不是实现__instancecheck__
.
If you want your objects to lie about their type in isinstance
checks (you really shouldn't), then the way to do that is to lie about __class__
, not implement __instancecheck__
.
class BadIdea(object):
@property
def __class__(self):
return tuple
print(isinstance(BadIdea(), tuple)) # prints True
顺便说一句,如果要获取对象的实际类型,请使用type
而不是检查__class__
或isinstance
.
Incidentally, if you want to get the actual type of an object, use type
rather than checking __class__
or isinstance
.
这篇关于__instancecheck__-覆盖不起作用-我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!