Encapsulation in Python — Python Technical Interview Questions & Answers

Encapsulation in Python

Encapsulation in Python

  • Encapsulation keeps data with the methods that are allowed to change it. On a bank account, Main should call deposit(100), not poke a.balance = -9. You hide the field with _balance or __balance and expose deposit / get_balance. The object protects its own rules — amount must be > 0.
  • Dry-run: Account starts at 0. deposit(100) → 100. deposit(-50) ignored. get_balance() prints 100. __balance is not for Main to touch. That is encapsulation for a fresher — not a long OOP essay.
  • Encapsulation in Python — output: 100. deposit(-50) ignored. __balance is not for Main to poke.
  Account
    __balance
         │ only via
         ▼
    deposit() / get_balance()

Technical Interview Tip: __balance + deposit that rejects negatives.

Code Examples for Encapsulation in Python

Example

# Encapsulation
class Account:
    def __init__(self):
        self.__balance = 0
    def deposit(self, amt):
        if amt > 0:
            self.__balance += amt
    def get_balance(self):
        return self.__balance

a = Account()
a.deposit(100)
a.deposit(-50)
print(a.get_balance())

Encapsulation in Python — output: 100. deposit(-50) ignored. __balance is not for Main to poke.

How to Explain Encapsulation in Python to an Interviewer

Explain Encapsulation as if you are teaching a junior — definition, then one tiny script.

Hide fields. Expose safe methods. deposit / get, not a.balance = -9.

What does the example print, and why?

Encapsulation in Python — output: 100

What mistake do freshers make with Encapsulation?

__balance name mangling.