The following methods can be defined to customize the meaning of
attribute access (use of, assignment to, or deletion of x.name
)
for class instances.
For performance reasons, these methods are cached in the class object
at class definition time; therefore, they cannot be changed after the
class definition is executed.
self
). name
is the attribute name.
This method should return the (computed) attribute value or raise an
AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object).
If __setattr__() wants to assign to an instance attribute, it should not simply execute "self.name = value" -- this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., "self.__dict__[name] = value".
See About this document... for information on suggesting changes.