为什么重写__getattribute__代理值搞砸了?

时间:2013-01-25 19:40:27

标签: python class inheritance getattribute new-style-class

为什么会这样?

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的实例,即使它试图包装它。

1 个答案:

答案 0 :(得分:2)

__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

这可能是您想要的行为,取决于您正在做什么。