How can I override class attribute access in python?
P.S. Is there a way to leave regular access to class attributes alone but calling a more specific exception on m
The __getattr__ magic method is called when the attribute doesn't exist on the instance / class / parent classes. You'd use it to raise a special exception for a missing attribute:
class Foo(object):
def __getattr__(self, attr):
#only called what self.attr doesn't exist
raise MyCustonException(attr)
If you want to customize access to class attributes, you need to define __getattr__
on 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 customize all attribute access, use the __getattribute__ magic method.