What is a descriptor, and how does @property use one?
A Python descriptor implements __get__, and optionally __set__ or __delete__, to control attribute access; @property is a data descriptor that wins over the instance dictionary.
Answer
Short answer
A descriptor is a class attribute that participates in attribute lookup through get, set or delete. @property uses that protocol as a data descriptor, which is why assigning an instance attribute cannot simply shadow it.
Keep descriptors explicit in the answer because that is the concept the interviewer is actually trying to test. A good descriptors explanation names the trade-off, the failure mode, and the evidence you would use before choosing.
Was this answer helpful?
Likely follow-ups
- Why can an instance attribute shadow a cached_property but not a property?
- What does __set_name__ save you from writing, and what did people do before it?
- Why does cached_property fail on a class that defines __slots__?
- When is a descriptor a better answer than validating in __init__ or __post_init__?
Related questions
- A list of a million small objects uses far more memory than the data inside them. Where is it going?mediumAlso on slots5 min
- You put @functools.lru_cache on a method to speed it up, and the service's memory keeps growing. Why, and which fix do you choose?mediumAlso on cached-property4 min
- A long-running Python service keeps climbing in memory and never comes back down. How do you work out where the memory went?hardAlso on slots5 min
- Find the cheapest flight from one city to another using at most K stops. Why does plain Dijkstra give the wrong answer?mediumSame kind of round: coding5 min