QA
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→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?