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 …
The post Python’s @property Decorator Explained appeared first on Django Central.