โ๏ธ@property, @setter, @deleter, __slots__LESSON~15 min
@property, @setter, @deleter, slots
Python properties let you expose computed or validated attributes with the clean access syntax of plain attributes. Instead of person.get_age(), you write person.age โ but behind the scenes, logic runs. __slots__ is a complementary feature that restricts what attributes a class can have, saving memory and preventing typos.
@property โ Computed Attributes
@property turns a method into an attribute-like accessor. Callers use obj.name (no parentheses):
@<name>.setter โ Validated Writes
Add a setter to allow writes, with validation:
Why private _radius? The setter uses self._radius for storage while the property is called radius. If you used self.radius in the setter, it would call the setter recursively โ infinite loop.
@<name>.deleter โ Cleanup on Delete
property() Function โ Old Style
Before decorators, you used property() directly. You may see this in legacy code:
Read-Only Properties
A property with no setter is read-only. Writing raises AttributeError:
slots โ Restricting Attributes and Saving Memory
By default, Python objects store attributes in a __dict__. With __slots__, you declare exactly which attributes the instance can have:
Memory savings: Slots replace the per-instance __dict__ with fixed-offset storage. For classes with millions of instances, this can save 30-50% memory:
slots with Inheritance
Slots and inheritance have caveats:
When to Use Properties
Use Case
Pattern
Computed values from other attributes
Read-only property
Validation on write
Property + setter with validation
Backward compatibility (old get_x() โ x)
Property with no code changes at call sites
Lazy computation (cache result)
Property that sets a private cache
Prevent attribute from being set
Read-only property (no setter)
Memory-critical code with many instances
__slots__
Knowledge Check
Why does a property's setter store data in `self._value` rather than `self.value`?
What does `__slots__` do to a class?
How do you create a read-only property (one that can be read but not written)?