Python's @property Decorator Explained

2 min read

Python provides a built-in @property decorator which makes usage of getter and setters much easier in Object-Oriented Programming.

Properties are useful because they allow us to handle both setting and getting values in a programmatic way but still allow attributes to be accessed as attributes.

Let's look at one example.

class Circle():
    def __init__(self, radius):
        self.diameter = 2*radius

    def circumference(self):
        return 3.14*self.diameter

    @property
    def radius(self):
        return self.diameter / 2

    @radius.setter
    def radius(self, radius):
        self.diameter = 2 * radius

In Python, @property is a built-in decorator that creates and returns a property object. The @property decorator is internally taking the bounded method as an argument and returns a descriptor object. That descriptor object then gets the same name of the old method therefore the setter method is bound to that method i.e. @radius.setter the method getter is referring too.

Now let's create an object and get its circumference

c = Circle(radius=2)
c.circumference()

Output:

12.56

Next, let's use the radius setter method.

c.radius = 3
c.circumference()

Output:

18.84

Properties solve several problems. The main one is that they allow you to substitute a method call for attribute access without changing the public API. That is important if you're dealing with large software projects where you can't break backward compatibility. You can easily modify your class to add getters and setters for the data without changing the interface, so you don't have to find everywhere in your code where that data is accessed and change that too.


PYTHON
author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read