Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 7 of 10 · Object-Oriented Programming (OOP)
Interview question

What is encapsulation and how do you achieve it? Encapsulation क्या है और इसे कैसे achieve करें?

Answer
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private (double underscore)
    
    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            return f'Deposited {amount}'
        return 'Invalid amount'
    
    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            return f'Withdrawn {amount}'
        return 'Insufficient funds'
    
    def get_balance(self):
        return self.__balance
    
    @property
    def balance(self):
        return self.__balance

# Using encapsulation
account = BankAccount(1000)
print(account.deposit(500))   # Deposited 500
print(account.withdraw(200))  # Withdrawn 200
print(account.get_balance())  # 1300

# Can't access directly
# print(account.__balance)  # AttributeError

# Single underscore (convention, not enforced)
class MyClass:
    def __init__(self):
        self._protected = 'Protected'  # Convention
        self.__private = 'Private'     # Name mangling
    
    def __private_method(self):
        return 'Private method'

obj = MyClass()
print(obj._protected)  # Accessible (convention)
# obj._MyClass__private  # Name mangling
class Student:
    def __init__(self, name, marks):
        self.__name = name
        self.__marks = marks
    
    def get_marks(self):
        return self.__marks
    
    def set_marks(self, marks):
        if 0 <= marks <= 100:
            self.__marks = marks
        else:
            print('Invalid marks')

student = Student('John', 85)
print(student.get_marks())  # 85
student.set_marks(90)
print(student.get_marks())  # 90

Was this answer clear?