Lecture 3 OOP Encapsulation
Lecture 3 OOP Encapsulation
LESSON 3_2
Encapsulation
© YCI – 2025.
BIT 1203 04/14/2025
What is Encapsulation?
2
Definition:
Encapsulation is the bundling of data and
methods within a class to protect data
integrity.
Key Benefits:
Data hiding
Improved security
Better code maintainability
Prevents accidental modification of critical
data
class Car:
def __init__(self, brand):
self.brand = brand # Public
attribute
def display(self):
return f"Car Brand: {self.brand}"
car = Car("Toyota")
print(car.brand) # ✅ Accessible
© YCI – 2025. 04/14/2025
Protected Attributes Example
5
class Car:
def __init__(self, brand, speed):
self.brand = brand
self._speed = speed # Protected
attribute
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private
def get_balance(self):
return self.__balance
account = BankAccount(1000)
print(account.get_balance()) # ✅
Allowed
# print(account.__balance) ❌ Error
© YCI – 2025. 04/14/2025
Getters and Setters
7
def get_age(self):
return self.__age