为什么覆盖__getattribute__代理一个价值螺丝起来isinstance? [英] Why does overriding __getattribute__ to proxy a value screw up isinstance?

查看:173
本文介绍了为什么覆盖__getattribute__代理一个价值螺丝起来isinstance?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会发生这种情况?

Why does this happen?

class IsInstanceScrewer(object):
    def __init__(self, value):
        self.value = value

    def __getattribute__(self, name):
        if name in ('value',):
            return object.__getattribute__(self, name)
        value = object.__getattribute__(self, 'value')
        return object.__getattribute__(value, name)

isinstance(IsInstanceScrewer(False), bool) #True
isinstance(IsInstanceScrewer([1, 2, 3]), list) #True

推荐答案

__ getattribute__这个类绝对不是bool的实例正在返回包装值的 __ class __ ,而不是自己的 __ class __

__getattribute__ is returning the __class__ of the wrapped value instead of its own __class__:

>>> class IsInstanceScrewer(object):
    def __init__(self, value):
        self.value = value

    def __getattribute__(self, name):
        print name
        if name in ('value',):
            return object.__getattribute__(self, name)
        value = object.__getattribute__(self, 'value')
        return object.__getattribute__(value, name)

>>> isinstance(IsInstanceScrewer(False), bool)
__class__
True
>>> isinstance(IsInstanceScrewer([1, 2, 3]), list)
__class__
True


$ b b

这可能是所期望的行为,或者不取决于你在做什么。

This may be desired behavior or not depending on what you're doing.

这篇关于为什么覆盖__getattribute__代理一个价值螺丝起来isinstance?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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