Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 149 · Object-Oriented Programming

Properties

Use Python's @property to create computed attributes, validate values with setters, make read-only attributes and keep a clean public interface for your classes.

In many languages you're told to hide every attribute behind get_x() and set_x() methods "just in case" you need logic later. Python takes a different approach: start with plain attributes, and if you ever need logic, turn the attribute into a property. Code that uses your class keeps writing obj.x and obj.x = 5, but now your method runs behind the scenes.

Properties are the Pythonic way to build computed attributes, validate values when they're assigned, and make attributes read-only. This lesson shows all three, plus the naming conventions that go with them.

A computed attribute

Put @property above a method that takes only self. The method then behaves like an attribute: you read it without parentheses.

Python A read-only computed property

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

area is computed fresh every time you read it, so it can never get out of sync with width and height. Storing self.area = width * height in __init__ would go stale the moment someone changed width.

Because there's no setter, the property is read-only. Try adding room.area = 100 at the end: Python raises an AttributeError explaining that the property has no setter.

Adding a setter for validation

To allow assignment, define a second method with the same name and decorate it with @<name>.setter. It receives the new value:

Python Validating with a setter

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line fails on purpose. A few things to notice:

  • The real value lives in self._target. The property is named target, so the stored value needs a different name, otherwise the setter would call itself forever. A leading underscore is the convention.
  • __init__ assigns self.target, not self._target. That routes the starting value through the setter, so even the constructor can't create an invalid thermostat.
  • The setter can also clean up input, here rounding to one decimal place.

Note: A single leading underscore (_target) means "internal, please don't touch" by convention. Python doesn't enforce it. Two leading underscores (__target) trigger name mangling, which renames the attribute to _Thermostat__target. That's meant to avoid clashes in subclasses, not for privacy, and you rarely need it.

Turning an attribute into a property later

This is the big win. Imagine version 1 of a class with a plain attribute, used in hundreds of places:

Python
class User:
    def __init__(self, email: str) -> None:
        self.email = email

Later you decide emails must be stored in lowercase and must contain @. You can add a property without changing any calling code:

Python Upgrading to a property

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Everything that wrote user.email or user.email = ... keeps working. That's why Python code rarely needs get_email()/set_email() methods: properties let you add logic at any time.

Properties and inheritance

Properties are inherited like any other attribute, so a subclass of User gets the same email validation for free. If a subclass needs stricter rules, the cleanest approach is to move the checks into a normal method that the setter calls, such as _validate_email(value), and override that method in the subclass. Redefining just the setter half of an inherited property is possible, but it's awkward and easy to get wrong.

Another common slip is forgetting that the getter and setter must share one name. If you write @property def email and then @email.setter def set_email, the setter is attached to a new property called set_email, and email stays read-only. Python gives no warning; you only notice when an assignment fails.

Deleters

There's a third decorator, @<name>.deleter, which runs on del obj.name. It's uncommon; you might use it to clear a cached value or reset to a default. Here's a short read-only snippet for reference:

Python
class Session:
    @property
    def token(self) -> str | None:
        return self._token

    @token.deleter
    def token(self) -> None:
        print("Logging out")
        self._token = None

Properties that depend on each other

Properties shine when one stored value can be viewed in several ways. Store one source of truth and compute the rest:

Python Two views of one value

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Only celsius is stored. Setting fahrenheit converts and stores Celsius, and every other reading follows automatically. kelvin has no setter, so it's read-only; try assigning to it and read the error.

Caching expensive values

If a computed value is slow to produce and the inputs don't change, recomputing it on every read is wasteful. functools.cached_property computes the value once, on first access, and stores the result on the instance:

Python cached_property

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

cached_property suits values that won't change, or where you control when to reset them with del. If the inputs can change at any time, use a plain @property so the result is never stale.

When to use a property

Properties are great, but they should still feel like attributes. Readers expect obj.x to be quick and free of surprises. Keep these guidelines in mind:

  • Use a property for cheap computed values, validation, and read-only views.
  • Use a regular method when the work is slow, has side effects (network, files, printing), or needs arguments. order.total is a good property; order.send_invoice() is clearly a method.
  • Don't wrap every attribute in a property up front. Start with plain attributes and upgrade only when you need logic.
  • Raise clear exceptions from setters, usually ValueError for a bad value and TypeError for a wrong type, so callers know exactly what went wrong. You learned how in Raising Exceptions.

Properties also work well with read-only data. A property that returns tuple(self._items) gives callers a snapshot they can loop over but can't change, while the class keeps full control of its internal list.

If you just need a class that stores fields with sensible defaults, the next lesson, Data Classes, will save you a lot of typing, and data classes can have properties too.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. How do you read a property called area on an object room?

    A property is accessed like a plain attribute, without parentheses. Python calls the method for you.
  2. 2. What happens when you assign to a property that has no setter?

    A property without a setter is read-only, so assignment raises an AttributeError.
  3. 3. Why does the setter store the value in self._target instead of self.target?

    self.target = ... triggers the setter, so storing under the same name would recurse endlessly. A different internal name breaks the loop.
  4. 4. Why assign self.target = target (not self._target) in __init__?

    Going through the property means even newly created objects are validated.
  5. 5. Which is the best candidate for a method rather than a property?

    Sending email is slow and has side effects, so it belongs in a method. Properties should be quick and free of surprises.

Summary

  • @property turns a method into an attribute you read without parentheses, perfect for computed values.
  • Add @name.setter to run code on assignment, usually validation or cleanup; store the data under an internal name like _name.
  • A property with no setter is read-only.
  • You can turn a plain attribute into a property later without changing calling code, so start simple.
  • functools.cached_property computes a value once and stores it; del obj.name clears it.
  • Keep properties cheap and side-effect free; use methods for slow work or actions.

Next: Data Classes, where @dataclass writes __init__, __repr__ and __eq__ for you.