Question presented to candidate:
"In Java you would write getRadius() and setRadius(). In Python people write @property. What does it do, how do you add a setter, and what is actually happening when I read circle.radius?"
What a strong answer should cover:
@propertyturns a method into a managed attribute: readingobj.areacalls the getter, no parentheses;@area.setterand@area.deleterhandle assignment anddel.- Why it exists: start with a plain public attribute and later add validation or computation without changing any calling code, so no Java-style getters are needed up front.
- A property without a setter is read-only; assigning raises
AttributeError(on 3.11: "property 'area' of 'Circle' object has no setter"). - Under the hood:
propertyis a class implementing the descriptor protocol; it is a data descriptor, so it wins over the instance__dict__in attribute lookup. .setterreturns a new property object, which is why the setter function must reuse the same name; store the value under a different name such as_radius.- Trade-offs: keep getters cheap and side-effect free; for an expensive value computed once,
functools.cached_property(a non-data descriptor that stores into__dict__).
Code / implementation expected: Yes β a class with a validated property (getter plus setter) and a read-only computed property.