Object-Oriented Programming
Properties
Managed attributes with @property decorator
Interview: Very common — tests encapsulation, computed properties, and the Pythonic approach to getters/setters
The @property decorator lets you define managed attributes — attributes that use getter, setter, and deleter methods but are accessed like regular attributes. This is the Pythonic way to add validation, computation, or side effects to attribute access without changing the API.
Why Properties?
- Start with simple attributes, upgrade to properties later without breaking API
- Add validation when setting values (e.g., positive numbers only)
- Compute values on-the-fly (e.g., area from radius)
- Add side effects (logging, caching) transparently
- Make attributes read-only by providing only a getter
Property Syntax
Use @property for the getter, @name.setter for the setter, and @name.deleter for the deleter. The property name must match. You can also use the property() function directly.
Computed Properties
Properties are perfect for derived values that depend on other attributes. Instead of storing redundant data, compute it on access. These are read-only (no setter needed).
Interview Tip
Know when to use properties vs methods. Properties should be used for values that look like attributes. If the operation is expensive, slow, or has side effects, use a regular method instead.
Use Cases
Input validation (positive numbers, valid ranges, type checking)
Computed/derived properties (area from radius, full_name from first+last)
Unit conversion (celsius/fahrenheit/kelvin)
Lazy loading / caching expensive computations
Read-only attributes (only provide getter, no setter)
Common Mistakes
Naming the property the same as the backing field (causes infinite recursion)
Using @property for expensive operations that should be methods
Forgetting to use the underscore prefix for the backing field (self._radius vs self.radius)
Defining setter without getter — @property requires getter first
Not understanding that property access looks like attribute access but runs code