Python getter and setter decorators
Let's say we want to have a class to define a circle with its radius and diameter as properties. We may do so naively as follows:
class NaiveCircle:
def __init__(self, radius):
self.radius = radius
self.diameter = radius * 2
def __repr__(self):
return f"Circle (r={self.radius}, d={self.diameter})"
In this case we maintain the radius and diameter of a circle in two different attributes. When we instantiate the class, there are no problems. However, it is important to realize that if we update the radius, the diameter should be updated accordingly and vice versa. Right now, this is not enforced so you need to do it manually:
c = NaiveCircle(8)
c # Circle (r=8, d=16)
# Update the radius
c.radius = 4
# We are left with an invalid circle
c # Circle (r=4, d=16)
# Manual patching is required...
c.diameter = c.radius * 2
This is poor design. The following better design makes two main improvements.
First, we define the diameter property directly in relation to the radius. Every time we access the diameter, we are sure that the returned value is two times the diameter. So if we set a new value for the radius, the diameter is updated accordingly. However, if we directly set a new value of the diameter, we can still break the mathematical relation between diameter and radius because the radius will not be updated. We can fix this by explicitly defining the setting behavior of the defined radius property. Consider the following example:
from functools import cached_property
class Circle:
def __init__(self, radius):
self.radius = radius
def __repr__(self):
return f"Circle (r={self.radius}, d={self.diameter})"
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
@cached_property
def area(self):
return 3.14 * self.radius ** 2
@property
def diameter(self):
return self.radius * 2
@diameter.setter
def diameter(self, diameter):
self.radius = diameter / 2
If we now set diameter, we do not directly set the diameter but instead first set the radius to half of the diameter. Because we already defined the diameter property as twice the radius, all is good:
c = Circle(8)
c # Circle (r=8, d=16)
# Halve the diameter, the radius is updated correctly!
c.diameter = 8
c # Circle (r=4.0, d=8.0)
The @cached_property used above is a variety of the @property decorator that caches the result of the computation so that it does not have to be recomputed each time the property is accessed.