Learn Python OOP encapsulation with Beginner's examples! Understand parent & child classes, method overriding, `super()`, and multilevel encapsulation.
Encapsulation is one of the core concepts of Object-Oriented Programming (OOP). It simply means hiding the internal details of an object and only showing necessary parts to the outside world. This helps keep data safe and makes code easier to maintain.
Encapsulation is the practice of binding data (variables) and methods (functions) that operate on the data into a single unit (a class), and restricting direct access to some of the object’s components.
Imagine a bank ATM machine.
🔁 This is encapsulation: hiding the complex internal logic and only exposing the necessary parts.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # private attribute
# Getter method
def get_balance(self):
return self.__balance
# Setter method with validation
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient balance or invalid amount")
# Using the class
account = BankAccount("Alice", 1000)
# Try to access private attribute directly (won't work as intended)
# print(account.__balance) # ❌ AttributeError
# Can't access __balance directly
print(account.get_balance()) # ✅ 1000
account.deposit(500)
print(account.get_balance()) # ✅ 1500
account.withdraw(2000) # ❌ Insufficient balance
__balance
is a private variable (name mangling in Python makes it hard to access directly).get_balance()
, deposit()
, and withdraw()
.Python doesn’t have strict private/public keywords, but we use naming conventions:
Type | Syntax | Access |
---|---|---|
Public | self.name |
Accessible everywhere |
Protected | _name |
Suggests limited access |
Private | __name |
Not directly accessible |
See also:
class TemperatureConverter:
def __init__(self):
self.__celsius = 0 # private attribute
def set_celsius(self, temp):
if temp < -273.15: # Absolute zero check
print("Temperature below absolute zero is not possible")
else:
self.__celsius = temp
def get_celsius(self):
return self.__celsius
def get_fahrenheit(self):
return (self.__celsius * 9/5) + 32
def get_kelvin(self):
return self.__celsius + 273.15
# Usage
thermo = TemperatureConverter()
thermo.set_celsius(25)
print(f"Celsius: {thermo.get_celsius()}") # 25
print(f"Fahrenheit: {thermo.get_fahrenheit()}") # 77.0
print(f"Kelvin: {thermo.get_kelvin()}") # 298.15
# Invalid temperature is prevented
thermo.set_celsius(-300) # Shows warning message
super()
, and multilevel inheritance.
👉 Learn more