Encapsulation
Encapsulation means keeping an object's data and the code that changes it together, and controlling how the outside world touches that data. It stops other parts of a program from putting an object into an invalid state, such as a negative bank balance.
The problem encapsulation solves
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
acc = Account("Imani", 5000)
acc.balance = -999999 # nothing stops this!
print(acc.balance)
Any code can change balance to any value. In a real system, money should only move through methods that check the rules. Encapsulation is about making that the normal, obvious way.
Public, protected and private names
Unlike Java or C++, Python has no truly private attributes. Instead it relies on naming conventions that every Python developer respects:
| Name | Meaning | Enforced? |
|---|---|---|
balance | Public: fine to use from outside | No restriction |
_balance | Protected ("internal"): please don't touch from outside the class or its subclasses | Convention only |
__balance | Private: name mangling makes it hard to reach from outside | Partly (renamed to _ClassName__balance) |
class Account:
def __init__(self, owner, pin):
self.owner = owner # public
self._transactions = [] # internal
self.__pin = pin # private (name-mangled)
def check_pin(self, attempt):
return attempt == self.__pin
acc = Account("Imani", "1234")
print(acc.check_pin("0000"), acc.check_pin("1234"))
try:
print(acc.__pin)
except AttributeError:
print("Cannot read __pin from outside the class")
print(acc._Account__pin) # the mangled name still works
Inside the class, self.__pin works normally. Outside, Python has renamed it to _Account__pin. This is meant to prevent accidents (especially name clashes in subclasses), not to provide security. Use a single underscore for most internal data, and double underscores only when you specifically need name mangling.
Controlling changes with methods
The simplest form of encapsulation: keep the data internal and offer methods that enforce the rules.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
def get_balance(self):
return self._balance
acc = Account("Imani", 5000)
acc.deposit(1500)
acc.withdraw(2000)
print(acc.get_balance())
Properties: the Pythonic way
Methods like get_balance() work, but Python offers something neater: properties. With the @property decorator, a method is used like an attribute (no brackets), and a matching .setter runs validation whenever someone assigns a value.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks # goes through the setter below
@property
def marks(self):
return self._marks
@marks.setter
def marks(self, value):
if not 0 <= value <= 100:
raise ValueError("Marks must be between 0 and 100")
self._marks = value
@property
def grade(self): # read-only: no setter
if self._marks >= 80:
return "A"
elif self._marks >= 65:
return "B"
elif self._marks >= 50:
return "C"
return "D"
baraka = Student("Baraka", 72)
print(baraka.marks, baraka.grade)
baraka.marks = 85
print(baraka.marks, baraka.grade)
try:
baraka.marks = 120
except ValueError as error:
print("Rejected:", error)
try:
baraka.grade = "A"
except AttributeError:
print("grade is calculated and cannot be set")
From the outside, baraka.marks looks like a plain attribute, but every assignment is checked. Because __init__ also assigns through self.marks, invalid marks are rejected even when the object is first created. grade has no setter, so it's read-only and always up to date.
Inside a property, store the value under a different name, usually with an underscore (self._marks). Writing self.marks = value inside the marks setter calls the setter again, and again, until Python stops with RecursionError.
Why bother?
- Valid data: rules live in one place, so objects can't be put into impossible states.
- Freedom to change: you can change how data is stored internally without breaking code that uses the class, as long as the public methods and properties stay the same.
- Clear design: the public names tell other programmers what they're meant to use.
Start with plain public attributes. Turn one into a property later if you need validation; code that uses obj.marks keeps working unchanged. You don't need getters and setters for everything.
Key points
- Encapsulation bundles data with the methods that protect it.
_namemeans "internal";__nametriggers name mangling; neither is real security.- Use
@propertyand@name.setterto validate values while keeping attribute-style access. - A property without a setter is read-only.
Tip: use the ← and → keys to move between pages.
