Python 为什么将uuGetAttribute_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?
为什么会发生这种情况Python 为什么将uuGetAttribute_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?,python,class,inheritance,getattribute,new-style-class,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.
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的实例,即使它试图对其进行包装。
\uuuu getattribute\uuuu
将返回包装值的\uuu class\uuuuuu
,而不是它自己的\uuu class\uuuuuuuu
:
>>> 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
这可能是您想要的行为,也可能不是,这取决于您正在做什么。注意,您需要将
('value')
更改为('value',)
(带逗号),否则您还没有创建元组,如果中的name('value')
是“value”的子字符串,则将为真。@BrenBarn:很好。在我的初始示例中,我曾经有更多的项目,但为了使它更简单,我减少了它们,并在mean timeBeat me中引入了一个bug。我正要发这个。(但您确实有一个领先的开始;-)作为旁注,与覆盖所有属性的整个销售相比,有时定义\uuuu getattr\uuuu
更好一些,只有在python无法通过正常方式找到属性时才会调用它。