Imagine you have a piggy bank. You put money IN through a small slot, and you can check how much is inside, but you can’t just reach in and grab money whenever you want. The piggy bank protects your money.Encapsulation works the same way:
Put data (like money) inside an object
Control HOW that data can be accessed or changed
Protect the data from being messed up accidentally
Simple Definition: Encapsulation = Wrapping data + methods together and controlling access to them.
class BankAccount: def __init__(self, owner_name): self.owner = owner_name self.__balance = 0 # Private! (notice the __) # Controlled way to add money def deposit(self, amount): if amount > 0: self.__balance += amount print(f"Deposited ${amount}. New balance: ${self.__balance}") else: print("Amount must be positive!") # Controlled way to take money def withdraw(self, amount): if amount > 0 and amount <= self.__balance: self.__balance -= amount print(f"Withdrew ${amount}. New balance: ${self.__balance}") else: print("Invalid amount or insufficient funds!") # Safe way to check balance def get_balance(self): return self.__balance# Now try to hack it!account = BankAccount("Alice")account.deposit(500) # Works! Balance is 500account.withdraw(100) # Works! Balance is 400account.withdraw(1000) # Blocked! Not enough moneyprint(account.get_balance()) # Shows 400# Try to hack directly?account.__balance = 1000000 # Seems to work...print(account.get_balance()) # Still 400! Python protected it!
class Student: def __init__(self, name, grade, diary_secret): self.name = name # Public: Everyone can see self._grade = grade # Protected: For class and children self.__diary = diary_secret # Private: Only for this class def read_diary(self, password): if password == "secret123": return self.__diary return "Wrong password!"student = Student("Bob", "A", "I like pizza")print(student.name) # Works: Bobprint(student._grade) # Works but shouldn't access: Aprint(student.__diary) # Error! Can't access privateprint(student.read_diary("secret123")) # Works: I like pizza