How can I override class attribute access in python?

How can I override class attribute access in python?

PS Is there a way to leave regular access to class attributes, but to throw a more specific exception on a missing attribute?

+7
source share
2 answers

The __getattr__ magic method __getattr__ called when the attribute does not exist in the instance / class / parent classes. You would use it to create a special exception for the missing attribute:

 class Foo(object): def __getattr__(self, attr): #only called what self.attr doesn't exist raise MyCustonException(attr) 

If you want to configure access to class attributes, you need to define __getattr__ in the metaclass / type:

 class BooType(type): def __getattr__(self, attr): print attr return attr class Boo(object): __metaclass__ = BooType boo = Boo() Boo.asd # prints asd boo.asd # raises an AttributeError like normal 

If you want to configure access to attributes, use the __getattribute__ magic method.

+13
source

agf's answer is correct, and in fact the answer I'm going to give is based on it and owes him a bit of credit.

Just to give more detailed information about the side of the attribute class, which is the part that is actually being questioned here (as opposed to the difference between __getattr__ and __getattribute__ ), I would like to add a link to the answer that I wrote to another similar question , which discusses in more detail the difference between class and instance attributes, how this is implemented, and why you need to use a metaclass to influence the search for class attributes.

+2
source

All Articles