Predict Data and Non-Data Descriptor Precedence
Core idea
For ordinary instance lookup, Python first finds a class attribute along the method resolution order. A descriptor with set or delete is a data descriptor; a readable data descriptor takes precedence over an instance dictionary entry. An instance dictionary entry can shadow a non-data descriptor, which has get but no setter or deleter. This explains why methods can be overridden on individual instances.
class Default: def __get__(self, obj, owner): return 'standard'class Ticket: lane = Default()t = Ticket()print(t.lane)t.lane = 'fast'print(t.lane, Ticket().lane)Assignment creates an instance entry; other instances still use the descriptor.
Protect a read-only property
class Report: @property def state(self): return 'ready'r = Report()r.__dict__['state'] = 'stale'print(r.state)try: r.state = 'new'except AttributeError: print('read-only')property is a data descriptor even without a user-defined setter. Its assignment hook raises AttributeError.
Common mistake
Do not assume every descriptor beats the instance dictionary. A non-data descriptor can be shadowed; custom getattribute can also change the normal lookup behavior.
Practice
Add a setter that raises AttributeError to Default, then insert lane directly into the instance dictionary. Predict and check the read result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data and nondata precedence
Check your understanding of data and nondata precedence.
What is printed?
class C: def f(self): return 'class'c=C(); c.f=lambda: 'instance'print(c.f())What is printed?
class C: @property def x(self): return 4c=C(); c.__dict__['x']=9print(c.x)Which hook makes a readable descriptor a data descriptor?
What wins over a non-data descriptor during ordinary instance lookup?