Intermediate LevelPython
How do you implement getter, setter, and deleter encapsulation in classes using @property decorators?
❓ Interview Prompt: Explain `@property`, `@field.setter`, `@field.deleter`, encapsulation, and managed attribute access syntax.
The '@property' decorator exposes getter and setter methods as standard attribute access syntax ('obj.age = 25'), preserving encapsulation:
Benefits:
Allows inserting validation logic or dynamic calculations without breaking existing client code that reads/writes properties directly!
Code Implementation Example
python
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError('Balance cannot be negative!')
self._balance = value
a = Account(100)
a.balance = 150 # Triggers @balance.setter validation!💡Encapsulating attribute access with @property getter and setter decorators.
🎯 Interview Key Takeaway
Use @property to add validation logic to attributes while keeping natural attribute access syntax.
#@property#getter#setter#Encapsulation#Intermediate
Back to all Python Questions→