Sub topic 2
Your First Property: The Getter
Assume you know how to define classes, use __init__, write basic decorators, and raise or catch exceptions. In Python, encapsulation means controlling how callers interact with an object's data. Python does not enforce private attributes, so a property provides a controlled attribute-style interface.
The `@property` Getter
A property is a method that callers use like an attribute. The @property decorator turns a method into a getter, which runs when the property is read.
class Celsius:
def __init__(self, degrees):
self._degrees = degrees
@property
def degrees(self):
return self._degrees
temperature = Celsius(25)
print(temperature.degrees) # 25The leading underscore signals that _degrees is an internal implementation detail. It is still accessible, but callers should use degrees instead.
Making an Attribute Read-Only
A property with only a getter cannot be assigned through its public name.
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
circle = Circle(2)
print(circle.radius)
try:
circle.radius = 5
except AttributeError:
print("radius is read-only")Assignment raises AttributeError because no setter exists. This is useful for values that callers may inspect but must not change directly.
Adding a Setter with Validation
Use @name.setter to define assignment behavior. The setter can reject invalid values before storing them.
class Celsius:
def __init__(self, degrees):
self.degrees = degrees
@property
def degrees(self):
return self._degrees
@degrees.setter
def degrees(self, value):
if value < -273.15:
raise ValueError("temperature is below absolute zero")
self._degrees = value
temperature = Celsius(25)
temperature.degrees = 30
print(temperature.degrees)
try:
temperature.degrees = -300
except ValueError as error:
print(error)The setter uses _degrees directly. Assigning self.degrees inside the setter would call the setter again and cause recursion.
Validating Through the Setter in `__init__`
The constructor assigns with self.degrees = degrees, so initial values follow exactly the same validation rule as later assignments.
Exercise
Why should __init__ assign self.degrees = degrees instead of self._degrees = degrees?
Show answer
It sends the initial value through the setter, so invalid objects cannot be created without validation.