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
@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()
Next, let’s use the radius setter method.
c.radius = 3 c.circumference()
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.