Python6 min read

Python Property Decorators

Create managed attributes with property decorators.

David Miller
December 18, 2025
0.0k0

Control attribute access.

Basic Property

```python class Person: def __init__(self, name): self._name = name @property def name(self): return self._name @name.setter def name(self, value): if not value: raise ValueError("Name cannot be empty") self._name = value

person = Person("Tom") print(person.name) # Tom person.name = "Sarah" # Uses setter ```

Read-Only Property

```python class Circle: def __init__(self, radius): self._radius = radius @property def area(self): import math return math.pi * self._radius ** 2

circle = Circle(5) print(circle.area) # 78.54 # circle.area = 100 # Error! No setter ```

Computed Property

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

temp = Temperature(25) print(temp.fahrenheit) # 77.0 temp.fahrenheit = 86 print(temp._celsius) # 30.0 ```

Validation Property

```python class BankAccount: def __init__(self, balance): self._balance = balance @property def balance(self): return self._balance @balance.setter def balance(self, value): if value < 0: raise ValueError("Balance cannot be negative") self._balance = value

account = BankAccount(1000) # account.balance = -500 # Error! ```

Remember

- @property for getters - @name.setter for setters - Use for validation and computed values

#Python#Advanced#OOP