Python @property decorator
1. What is @property
The @property decorator allows a method to be accessed like an attribute while still providing controlled logic behind the scenes.
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
p = Person("Alice")
print(p.name) # AliceTransforms method calls into attribute-style access.
2. Encapsulation Using @property
class Product:
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
item = Product(100)
print(item.price)Prevents direct access to internal variables while still exposing data.
3. Read-Only Property
Computed properties behave like read-only attributes.
4. Using @property with Setter
Allows controlled updates with validation.
5. @property with Deleter
Supports controlled deletion of attributes.
6. Computed Property Example
Encapsulates derived data logic.
7. Difference: @property vs Normal Method
@property improves readability and API design.
8. Enforcing Data Integrity
Common pattern for safe state management.
9. Lazy Evaluation with @property
Data is calculated only when required.
10. Enterprise-Style Implementation Example
Provides clean API, robust validation, and business-rule enforcement.
Summary
@property
Access method as attribute
@setter
Controlled data update
@deleter
Controlled deletion
Encapsulation
Protects internal state
Lazy Computation
Improves performance
Last updated