Sub topic 1
Where attributes live: instance and class __dict__
Prerequisites
This chapter assumes you can write Python classes and create instances. You should know the difference between an instance attribute and a class attribute, and you should have seen basic inheritance and special (dunder) methods such as __init__. Later chapters build on the namespaces described here.
Two namespaces, two dictionaries
Every attribute you read with obj.name is stored somewhere. In most Python objects, that place is a dictionary called __dict__. Two of these matter for attribute lookup:
- The instance
__dict__holds values that belong to one object, usually set in__init__. - The class
__dict__holds what the class body defines: methods, class attributes, and later, descriptors.
class Dog:
species = "canine"
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof"
rex = Dog("Rex")
print(rex.__dict__)
print("species" in Dog.__dict__)
print("speak" in Dog.__dict__)
print("speak" in rex.__dict__)The output is:
{'name': 'Rex'}
True
True
FalseThe instance dictionary contains only name. The method speak and the attribute species live on the class and are shared by every instance. Python does not copy them into each object.
Assignment writes to the instance
A plain assignment obj.name = value stores the value in the instance __dict__. It does not change the class, even when the class has an attribute with the same name.
class Counter:
step = 1
c = Counter()
c.step = 5 # creates an entry in the instance dict
print(c.step) # 5
print(Counter.step) # 1
print(c.__dict__) # {'step': 5}
del c.step # removes the instance entry
print(c.step) # 1, the class value is visible againThis is called shadowing. The instance entry hides the class entry of the same name for that one object. Deleting the instance entry makes the class value visible again.
Reading checks both places
When you read rex.species, Python looks in the instance __dict__ first. If the name is missing there, it looks in the class. This simple model explains most everyday behavior. It is incomplete, because descriptors can override it, and later chapters refine it.
Inspecting namespaces safely
Use vars(obj) as a shorthand for obj.__dict__. Class dictionaries are exposed as read-only mappingproxy objects, so you cannot assign into Dog.__dict__ directly. Use setattr(Dog, "x", 1) or Dog.x = 1 instead.
class Box:
pass
print(type(Box.__dict__).__name__) # mappingproxy
try:
Box.__dict__["size"] = 3
except TypeError as e:
print("cannot write:", e)
Box.size = 3
print(Box().size) # 3Not every object has an instance __dict__. Classes that declare __slots__ do not, and many built-in types such as int do not either. A later chapter covers __slots__.
Common mistakes
- Expecting
obj.__dict__to list methods. It lists only instance data. - Mutating a shared class-level list through an instance, such as
obj.items.append(1). This changes the list on the class for every instance, because no assignment happens. - Assuming
dir(obj)andobj.__dict__match.dirmerges names from the instance and the class hierarchy.
Exercise
Given class A: x = 1 and a = A(), what do a.x, A.x and a.__dict__ show after running a.x = 2?
Show answer
a.x is 2, A.x is still 1, and a.__dict__ is {'x': 2}. The assignment created an instance entry that shadows the class attribute.
Exercise
Why does Box.__dict__["size"] = 3 fail while Box.size = 3 works?
Show answer
A class __dict__ is a read-only mappingproxy. Assigning through the class uses type.__setattr__, which updates the class namespace properly.