Sub topic 1
Where Attributes Live: Instance and Class `__dict__`
Prerequisites
You should know how to define Python classes, create instances, use inheritance, and distinguish instance attributes from class attributes.
Instance and Class Namespaces
Every ordinary Python object has a namespace, usually exposed as obj.__dict__. It maps attribute names to values stored specifically on that instance. A class also has a namespace, exposed as Class.__dict__. It contains methods, class attributes, and other objects assigned in the class body.
class User:
role = "reader"
def __init__(self, name):
self.name = name
user = User("Mina")
print(user.__dict__) # {'name': 'Mina'}
print(User.__dict__["role"]) # reader
print(user.role) # readerrole is found on the class because it is not in user.__dict__. All User instances can read it, but assigning user.role = "admin" creates an instance entry that normally affects only user.
Searching the Class Hierarchy with the MRO
If an attribute is not in the instance namespace, Python searches the class hierarchy. The method resolution order, or MRO, is the ordered list of classes Python checks. You can inspect it with User.__mro__.
class Account:
category = "basic"
class AdminAccount(Account):
pass
print(AdminAccount.__mro__)
print(AdminAccount.category) # basicPython checks AdminAccount, then Account, and then their base classes. The first matching name normally supplies the value.
What `obj.name` Actually Calls
Attribute syntax calls type(obj).__getattribute__(obj, "name"). The default implementation coordinates instance lookup, class lookup, and special lookup rules. A class can override __getattribute__, but doing so incorrectly can cause infinite recursion.
If normal lookup raises AttributeError, Python may call obj.__getattr__("name") as a fallback. __getattr__ is not called for successful lookups.
The Descriptor Protocol
A descriptor is an object stored on a class that controls attribute access. Its methods include __get__, __set__, and __delete__. For example, functions use __get__ to become bound methods when accessed through an instance. property uses the same protocol to run getter and setter code.
Exercise
Where does Python find user.name when name is stored in user.__dict__?
Show answer
The lookup starts through type(user).__getattribute__, and the instance namespace supplies the value unless a higher-priority descriptor intercepts it.