Member-only story
Understanding Python Property Decorators: Getters, Setters
Introduction:
The property decorator in Python is a powerful feature that allows you to define “getter”, “setter” methods for class attributes without explicitly calling them as methods. Instead, you can access, modify, or delete the attribute as if it were a regular class property. The property decorator is used to define methods that can be accessed as if they were attributes, allowing you to implement custom behavior when getting, setting, or deleting their values.
In this article, we’ll explore Python property decorators in detail, covering:
- The
@property
decorator (getter) - The
@<attribute>.setter
decorator (setter)
Getter — @property
:
The @property
decorator is used to define a method that acts as a "getter" for an attribute. When you access the attribute, the method decorated with @property
will be called automatically. This is useful for calculations or other actions that need to occur when the attribute is accessed.
Example:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
print("Getting the radius")
return self._radius
c = Circle(5)
print(c.radius) #…