Skip to the solution
MediumDSA5 min read

What is the @property decorator?

1.0k views

The problem

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:

  • @property turns a method into a managed attribute: reading obj.area calls the getter, no parentheses; @area.setter and @area.deleter handle assignment and del.
  • 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: property is a class implementing the descriptor protocol; it is a data descriptor, so it wins over the instance __dict__ in attribute lookup.
  • .setter returns 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.

  • property

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonGetter, validating setter, deleter and a read-only computed property
PythonUnder the hood: the descriptor, setter copies, property() and cached_property

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 49 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

Why is using a mutable default argument dangerous?

Continue