A class attribute is a variable bound to a class object rather than to a specific instance of that class. It is defined within the class body, outside of any instance methods (such asDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
__init__), and its memory allocation is shared across all instances instantiated from that class.
Because class attributes are defined within the lexical scope of the class body, they reside in the class’s namespace (ClassName.__dict__) rather than the instance’s namespace (instance.__dict__).
Attribute Resolution Order
When you access an attribute via an instance (obj.attribute), Python invokes __getattribute__ and follows a strict resolution order:
- It first checks the class hierarchy, traversing the Method Resolution Order (
__mro__), for a data descriptor (an object defining both__get__and__set__methods, such as a@property). - If no data descriptor is found, it checks the instance’s namespace (
obj.__dict__). - If the attribute is not found in the instance namespace, it searches the class hierarchy sequentially according to the MRO (where the immediate class is simply the first element in this sequence), looking for a non-data descriptor or a regular class attribute.
Modification and Shadowing
The behavior of modifying a class attribute depends strictly on whether the modification is performed via the class object or the instance object, and whether the assignment operation is a reassignment or a mutation. 1. Modifying via the Class Assigning a new value directly to the class attribute updates the value in the class namespace. This change is immediately reflected across all instances that do not have a shadowing instance attribute.__dict__. This new instance attribute “shadows” the class attribute for that specific object during lookup (Step 2 of the resolution order).
list or dict), calling a mutating method (e.g., .append(), .update()) via an instance modifies the shared object in place. Because no assignment (=) occurs to the attribute name itself, Python does not create a shadowing instance attribute.
Master Python with Deep Grasping Methodology!Learn More





