__instancecheck__-覆盖不起作用-我做错了什么? [英] __instancecheck__ - overwrite shows no effect - what am I doing wrong?

查看:133
本文介绍了__instancecheck__-覆盖不起作用-我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使我的类作为另一个对象出现,以规避我正在使用的程序包中的惰性类型检查.更具体地说,我试图使我的对象显示为另一个对象的实例(在本例中为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.

为了实现这一点,我计划根据__isinstance__方法. rel ="nofollow noreferrer">文档,应该完全按照我的意愿进行.但是,似乎我不知道该怎么做,因为我的尝试没有成功.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆