Python Encapsulation — Complete Cheat Sheet
What is Encapsulation?
Encapsulation is an OOP concept used to hide the internal data of a class and protect it from being accessed or modified directly.
In Python, encapsulation is handled using:
- Public Members — accessible everywhere
- Protected Members — single underscore (
_value) - Private Members — double underscore (
__value)
Public Members
Public attributes and methods can be accessed from anywhere in the program.
class Person:
def __init__(self, name):
self.name = name # Public attribute
p = Person("Emil")
print(p.name)Protected Members (_variable)
Identified using a single underscore. They are meant for internal use but still technically accessible.
class Student:
def __init__(self):
self._grade = "A" # Protected
s = Student()
print(s._grade) # Accessible but not recommendedPrivate Members (__variable)
Private attributes cannot be accessed directly from outside the class. They use double underscores.
class Bank:
def __init__(self, balance):
self.__balance = balance # Private attribute
b = Bank(2000)
print(b.__balance) # Error!Private attributes use name mangling. Python renames __balance → _Bank__balance.
print(b._Bank__balance) # Works, but not recommended
Getters and Setters (Safe Access)
Getters & Setters safely control access to private data.
class Bank:
def __init__(self, balance):
self.__balance = balance
def get_balance(self): # Getter
return self.__balance
def set_balance(self, amount): # Setter
if amount >= 0:
self.__balance = amount
else:
print("Invalid amount")
b = Bank(2000)
print(b.get_balance())
b.set_balance(5000)
print(b.get_balance())Private Methods
Methods can also be private using double underscores.
class Car:
def __start_engine(self):
print("Engine started!")
def drive(self):
self.__start_engine()
print("Car is moving")
c = Car()
c.drive()Levels of Encapsulation
| Type | Syntax | Accessibility |
|---|---|---|
| Public | name | Accessible everywhere |
| Protected | _name | Accessible, but meant for internal use |
| Private | __name | Not directly accessible, uses name mangling |
Summary
- Encapsulation hides internal data and methods
- Public: free access
- Protected: intended for internal use
- Private: fully hidden (via name mangling)
- Use Getters/Setters for safe access
- Makes your code secure and prevents accidental modification