Using special methods for attribute access

We'll look at the three canonical special methods for attribute access: __getattr__(), __setattr__(), and __delattr__(). Additionally, we'll acknowledge the __dir__() method to reveal attribute names. We'll defer __getattribute__() to the next section.

The default behavior shown in the first section is as follows:

  • The __setattr__() method will create and set attributes.
  • The __getattr__() method will do two things. Firstly, if an attribute already has a value, __getattr__() is not used; the attribute value is simply returned. Secondly, if the attribute does not have a value, then __getattr__() is given a chance to return a meaningful value. If there is no attribute, it must raise an AttributeError exception. ...

Get Mastering Object-oriented Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.