How do I properly override __setattr__ and __getattribute__ on new-style classes in Python?

后端 未结 2 1587
慢半拍i
慢半拍i 2020-12-08 06:52

I want to override my Python class\'s __getattribute__ and __setattr__ methods. My use case is the usual one: I have a few special names that I wan

相关标签:
2条回答
  • 2020-12-08 07:02

    SomeSuperclass.__setattr__(self, name, value) ?

    0 讨论(0)
  • 2020-12-08 07:20

    It's

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

    in Python 2, or

    super().__setattr__(name, value)
    

    in Python 3.

    Also, raising AttributeError is not how you fall back to the default behavior for __getattribute__. You fall back to the default with

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

    on Python 2 or

    return super().__getattribute__(name)
    

    on Python 3.

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

    See the documentation on Customizing Attribute Access.

    0 讨论(0)
提交回复
热议问题