Creating Read-Only Computed Attributes
In this lesson, you will learn how to design object attributes that calculate values on the fly based on other instance data, ensuring they remain protected from direct modification.
Why Use Computed Attributes?
Sometimes an object has internal data that changes, and you need a value that stays perfectly in sync with those changes. Instead of storing that result in a variable (which might get "out of date" if the source data changes), you can define a method that performs the calculation whenever the value is requested. By using the @property decorator without a corresponding setter method, you create a "read-only" attribute that behaves like a variable but acts like a function.
Implementation Example
Imagine a Rectangle class. You want to store the width and height, but you also want an area attribute that is always accurate, even if the dimensions are updated.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
# This calculates the result dynamically
return self.width * self.height
rect = Rectangle(10, 5)
print(rect.area) # Output: 50
# Because there is no @area.setter, the following will raise an AttributeError:
# rect.area = 100
How It Works
- The Decorator: By placing
@propertyabove a method, you tell Python that you want to access this method as if it were a standard attribute (usingrect.areainstead ofrect.area()). - Read-Only Nature: Because you did not define a
@area.setter, the attribute cannot be overwritten from outside the class. If a user tries to assign a value torect.area, Python will raise an error, protecting the integrity of your calculation. - Dynamic Logic: Every time you access
rect.area, the code inside the method runs. If you changerect.width, the very next time you callrect.area, it will automatically reflect the updated dimension.
This approach keeps your objects clean and prevents data inconsistency.
Key Takeaway: Use the @property decorator without a setter to expose calculated values as read-only attributes that stay perfectly in sync with your object's internal state.