Getters, setters and @property

Adding validation to an attribute without changing a single line of the code that uses it.

What you'll learn
  • Explain how attribute access uses an object's __dict__
  • Add validation with getter and setter methods, and see why that breaks callers
  • Use @property to keep the attribute syntax while running code behind it

The 04property/ folder tells a three-step story about one class, a temperature in degrees Celsius.

Step 1: a plain attribute. Callers read and write human.temprature directly. Internally that is a dictionary lookup — human.__dict__ is {'temprature': 37} — and to_fahrenheit() returns 98.60000000000001, a reminder that 37 × 1.8 is not exact in binary floating point.

Step 2: getters and setters. Now a rule arrives: nothing may be colder than −273.15 °C. The Java-style fix hides the value as _temperature and adds get_temperature() and set_temperature(), which raises a ValueError for Celsius(-300). It works, but every caller that wrote obj.temperature must be rewritten — the change is not backwards compatible.

Step 3: properties. A property keeps the attribute syntax and runs methods behind it:

class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature      # goes through the setter

    @property
    def temperature(self):
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273.15:
            raise ValueError("Temperature below -273.15 is not possible")
        self._temperature = value

Old code that reads human.temperature or assigns to it keeps working, and now every assignment is validated — including the one in __init__, so even Celsius(-300) is rejected. 01property_class.py builds the same thing without decorator syntax, temperature = property(get_temperature, set_temperature), which makes clear that a property is an object living on the class.

That is also why it works: when Python looks up human.temperature, it finds a property on the class before checking the instance’s __dict__, and calls its getter. Objects like this, which intercept attribute access, are called descriptors; methods and @staticmethod use the same mechanism.

A property without a setter is read-only, which is the cleanest way to expose a computed value such as fahrenheit. e_getter_setter.py shows the minimal version on a property named valuee.

Try it yourself. Add a read-only fahrenheit property to the final Celsius class, and check that human.fahrenheit = 50 raises AttributeError. Then add a setter that converts back to Celsius, so both attributes stay in sync.

View source on GitHub →