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

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read