2.1.1 Encapsulation
Encapsulation (Python OOP)
Encapsulation means keeping data and the methods that use that data together inside a class, and controlling how the data can be changed.
Beginner way to think:
- You don’t want random code to directly change important variables.
- You want changes to happen through safe methods that check rules.
Real-Life Analogy
A bank account has a balance.
- You should not be able to do: “balance = -999999” by mistake.
- Instead you use:
deposit()andwithdraw()which apply rules.
Example: A BankAccount with Rules
PYTHON
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = float(balance) # underscore: treat as internal
def deposit(self, amount):
amount = float(amount)
if amount <= 0:
raise ValueError("Deposit amount must be positive")
self._balance += amount
def withdraw(self, amount):
amount = float(amount)
if amount <= 0:
raise ValueError("Withdraw amount must be positive")
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
def get_balance(self):
return self._balance
acc = BankAccount("Ayesha", 500)
acc.deposit(250)
acc.withdraw(100)
print(acc.get_balance())
What encapsulation did for us:
acc._balanceis treated as internal.- Users are guided to use
deposit()/withdraw(). - The object protects itself from invalid states.
Using @property (Pythonic Encapsulation)
Python lets you expose a value like an attribute but still enforce rules.
PYTHON
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
value = float(value)
if value < -273.15:
raise ValueError("Temperature can't go below absolute zero")
self._celsius = value
t = Temperature(25)
t.celsius = 30
print(t.celsius)
Here the outside code uses t.celsius, but internally we still validate and store it safely.
Common Beginner Mistakes
-
Thinking Python has strict private variables
- Python uses conventions:
_namemeans internal. - You can still access it, but you shouldn’t.
- Python uses conventions:
-
Making everything public
- If you let everything be changed freely, your objects can become inconsistent.
Quick Practice
Create a class Student:
- store
_marks(0 to 100) - use a property
marksthat rejects invalid values - add a method
is_passed()that returnsTrueif marks >= 50