如何在 Python 中的新型类上正确覆盖 __setattr__ 和 __getattribute__?

新手上路,请多包涵

我想覆盖我的 Python 类的 __getattribute____setattr__ 方法。我的用例是常见的:我有一些我想要处理的特殊名称,我想要其他任何东西的默认行为。对于 __getattribute__ ,似乎我可以通过提高 AttributeError 来请求默认行为。但是,我怎样才能在 __setattr__ 中实现相同的目标?这是一个简单的例子,实现了一个具有不可变字段“A”、“B”和“C”的类。

 class ABCImmutable(SomeSuperclass):
    def __getattribute__(self, name):
        if name in ("A", "B", "C"):
            return "Immutable value of %s" % name
        else:
            # This should trigger the default behavior for any other
            # attribute name.
            raise AttributeError()

    def __setattr__(self, name, value):
        if name in ("A", "B", "C"):
            raise AttributeError("%s is an immutable attribute.")
        else:
            # How do I request the default behavior?
            ???

用什么代替问号?对于旧式类,答案显然是 self.__dict__[name] = value ,但文档表明这对于新式类是错误的。

原文由 Ryan C. Thompson 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 782
2 个回答

它是

super(ABCImmutable, self).__setattr__(name, value)

在 Python 2 中,或者

super().__setattr__(name, value)

在 Python 3 中。

此外,提高 AttributeError 并不是 您退回到 __getattribute__ 的默认行为的方式。你回退到默认值

return super(ABCImmutable, self).__getattribute__(name)

在 Python 2 或

return super().__getattribute__(name)

在 Python 3 上。

Raising AttributeError the default handling and goes to __getattr__ , or just produces an AttributeError in the calling code if there’s no __getattr__ .

请参阅有关 自定义属性访问 的文档。

原文由 Hank Gay 发布,翻译遵循 CC BY-SA 3.0 许可协议

SomeSuperclass.__setattr__(self, name, value)

原文由 Jeannot 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题