【问题标题】:Why does overriding __getattribute__ to proxy a value screw up isinstance?为什么覆盖 __getattribute__ 来代理一个值会破坏 isinstance?
【发布时间】:2013-01-09 20:27:57
【问题描述】:

为什么会这样?

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

【问题讨论】:

  • 请注意,您需要将('value') 更改为('value',)(带逗号),否则您还没有创建元组,如果name 是“的子字符串,if name in ('value') 将为真价值”。
  • @BrenBarn:很好的收获。在我最初的示例中,我曾经有更多的项目,但减少了它们以使其更简单,同时引入了一个错误

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


【解决方案1】:

__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

这可能是所需的行为,也可能不是,取决于您在做什么。

【讨论】:

  • 打败我。我正要发这个。 (但你确实有一个领先的开始;-)
  • 附带说明,而不是全部覆盖所有属性,有时定义 __getattr__ 会更好一些,它仅在 python 无法通过正常方式找到属性时调用。
猜你喜欢
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 2021-09-12
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多