为什么重写\uGetAttribute_Uu来代理一个值会使isinstance出错?

2024-10-01 22:32:14 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么会这样?在

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

该类绝对不是bool的实例,即使它试图包装它。在


Tags: nameinselftruereturnifobjectinit
1条回答
网友
1楼 · 发布于 2024-10-01 22:32:14

__getattribute__返回包装值的__class__,而不是它自己的__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

这可能是你想要的行为,也可能不取决于你在做什么。在

相关问题 更多 >

    热门问题