Back
+15 XP
Concept

The `@property` Decorator: Clean Getters & Setters

`@property` turns a method into a read-only attribute getter. Pair it with `@name.setter` to validate incoming data without breaking dot syntax.

python
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    @property
    def fahrenheit(self):
        return (self._celsius * 9/5) + 32

t = Temperature(0)
print(t.fahrenheit)  # 32.0 (Accessed like an attribute!)

# 6. The `@property` Decorator: Clean Getters & Setters `@property` turns a method into a read-only attribute getter. Pair it with `@name.setter` to validate incoming data without breaking dot syntax: ```python class Temperature: def __init__(self, celsius): self._celsius = celsius @property def fahrenheit(self): return (self._celsius * 9/5) + 32 t = Temperature(0) print(t.fahrenheit) # 32.0 (Accessed like an attribute!) ``` This ensures backward compatibility: Start with plain attributes (`self.price = 10`). If you later need to validate that price is positive, convert it to a `@property` without breaking external code using `obj.price`.

Checkpoint

Why is `@property` preferred over Java-style `get_temperature()` methods in Python?

Practice

Create a class `Circle(radius)` with a `@property` named `diameter` that returns `self.radius * 2`. Instantiate `Circle(5)` and print its `diameter`.

Terminal
01
Tap code blocks below to assemble
Available Blocks