KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I want to override my Python class's __getattribute__ and __setattr__ methods. My use case is the usual one: I have a few special names that I want to handle, and I want the default behavior for anything else. For __getattribute__ , it seems that I can request the default behavior simply by raising AttributeError . However, how can I achieve the same in __setattr__ ? Here is a trivial example, implementing a class with immutable fields "A", "B", and "C". class ABCImmutable(SomeSuperclass): def __getattribute__(self, name): if name in ("A", "B", "C"): return "Immutable value of %s" % name else: # This should trigger the default behavior for any other # attribute name. raise AttributeError() def __setattr__(self, name, value): if name in ("A", "B", "C"): raise AttributeError("%s is an immutable attribute.") else: # How do I request the default behavior? ??? What goes in place of the question marks? With old-style classes, the answer was apparently self.__dict__[name] = value , but documentation indicates that this is wrong for new-style classes.
Tags (comma-separated)
Save Edits
Cancel