为什么会这样?
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的实例,即使它试图包装它。
答案 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
这可能是您想要的行为,取决于您正在做什么。