Member-only story

Understanding the property Decorator in Python

Allwin Raju
2 min readFeb 7, 2025

--

Photo by Artturi Jalli on Unsplash

Python provides a powerful way to manage class attributes using the @property decorator. This feature lets you define getters, setters, and deleters while maintaining a clean and Pythonic interface. In this blog post, we'll explore how @property works, why it's useful, and how to apply it effectively in your code.

Read for free: https://allwin-raju.medium.com/understanding-the-property-decorator-in-python-1e5a7737b0fc?sk=6ca6f9af00bfff7e6809d8b66c26bce3

What is @property?

The @property decorator allows a method to be accessed like an attribute, making it possible to define computed properties while maintaining encapsulation. This helps enforce data validation and ensures attributes are modified in a controlled manner.

Basic Example

Let’s start with a simple class that uses @property:

class Person:
def __init__(self, name):
self._name = name

@property
def name(self):
"""Getter method for name"""
return self._name

@name.setter
def name(self, value):
"""Setter method for name"""
if not isinstance(value, str):
raise ValueError("Name must be a string")
self._name = value

@name.deleter
def name(self):
"""Deleter method for…

--

--

No responses yet