python / intermediate
Snippet
Property Decorators for Encapsulation
The @property decorator allows you to define methods that can be accessed like attributes, providing a clean way to implement validation and encapsulation in classes.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
class Circle:def __init__(self, radius):self._radius = radius@propertydef radius(self):return self._radius@radius.setterdef radius(self, value):if value < 0:raise ValueError('Radius cannot be negative')self._radius = value
Breakdown
1
@property
Turns a method into a getter for the attribute.
2
@radius.setter
Defines logic to be executed when the attribute is assigned a value.