Encapsulation in Python OOP: A Beginner's Guide
Learn Python OOP encapsulation with Beginner's examples! Understand parent & child classes, method overriding, `super()`, and multilevel encapsulation.
Table of Contents
- What is Encapsulation?
- Why Use Encapsulation?
- Example 1: Basic Encapsulation
- Access Levels in Python
- Example 2: Real-World Usage - Temperature Converter
-
Summary
- Tasks
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.
π§ What is Encapsulation?
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.
π§ Why Use Encapsulation?
- To protect data from unwanted changes
- To control access using getters and setters
- To make your code modular, reusable, and easy to debug
π¦ Example in Real Life:
Imagine a bank ATM machine.
- You insert a card and enter a PIN to withdraw money.
- You canβt see the inner workings of the machine.
- You interact only with buttons and screen (public interface).
π This is encapsulation: hiding the complex internal logic and only exposing the necessary parts.
Example 1: Basic Encapsulation
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π§± How It Works:
__balanceis a private variable (name mangling in Python makes it hard to access directly).- You access it only through methods like
get_balance(),deposit(), andwithdraw().
See also:
- Understanding Name Mangling in Python - Syntax and Purpose
- Python Comparison Chaining Explained (0 < amount < balance) with Examples
π Access Levels in Python:
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:
Example 2: Real-World Usage - Temperature Converter
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π― Real-World Usage Benefits
- Banking Systems: Protect account balances while allowing deposits/withdrawals
- User Authentication: Hide password storage details while providing login methods
- Game Development: Control character attributes like health points
- E-commerce: Manage product inventory with validation rules
β Tips
- Remember, in Python, encapsulation is more about convention than enforcement. The single and double underscore prefixes are signals to other programmers about how attributes should be used, not strict access controls.
β Summary
- Encapsulation is about hiding internal data and exposing only whatβs needed.
- Use methods to control access to internal data.
- It helps keep your code clean, secure, and maintainable.
π Related Topics
- Classes and Objects β Learn how to create and use classes in Python with practical examples. π Learn more
- Inheritance in Python β Learn Python OOP inheritance with Beginner's examples! Understand parent & child classes, method overriding,
super(), and multilevel inheritance. π Learn more - Polymorphism β Learn polymorphism in Python OOP with practical examples. Understand method overriding, duck typing, and operator overloading for flexible and reusable code. π Learn more
- Abstraction and Interfaces β Learn about abstraction in python π Learn more
- Protected Access Level β Learn about Protected Access Level in python π Learn more