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 missing attribute?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:If you want to customize access to class attributes, you need to define
__getattr__on the metaclass / type:If you want to customize all attribute access, use the
__getattribute__magic method.