Welcome to our comprehensive guide on Encapsulation in Python! This lesson is designed to help you understand the concept from scratch, so even if you're new to programming, you'll find this tutorial helpful.
Encapsulation is a fundamental programming concept that involves bundling data (variables) and functions (methods) that operate on that data into a single unit - a class. In Python, classes are used to create objects, which are instances of those classes. Let's dive into the details.
class MyClass:
def __init__(self, name): # Constructor
self.name = namemy_obj = MyClass("John Doe")Python has four access modifiers: public, private, protected, and no access. However, Python doesn't explicitly support private and protected access modifiers like other languages. Instead, it uses naming conventions to achieve similar functionality.
class MyClass:
public_var = "I'm public"class MyClass:
def __init__(self):
self.__private_var = "I'm private"
def display_private(self):
print(self.__private_var)Methods are functions that are defined within a class. They are used to perform actions on the class's data.
class MyClass:
def greet(self):
print(f"Hello, {self.name}!")
my_obj.greet() # Output: Hello, John Doe!Encapsulation protects the data from being directly modified by external code, ensuring that the data is used and modified correctly. By using encapsulation, you can:
Let's create a BankAccount class that encapsulates a bank account's balance and methods for depositing and withdrawing money:
class BankAccount:
def __init__(self, balance=0):
self._balance = balance
def deposit(self, amount):
if amount > 0:
self._balance += amount
print(f"Deposited {amount} successfully.")
else:
print("Invalid deposit amount.")
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
print(f"Withdrew {amount} successfully.")
else:
print("Insufficient balance.")
def check_balance(self):
print(f"Current balance: {self._balance}")
# Create a bank account with an initial balance of 1000
my_account = BankAccount(1000)
my_account.deposit(500)
my_account.withdraw(200)
my_account.check_balance() # Output: Current balance: 1300In this example, we have encapsulated the bank account's balance and provided methods to deposit and withdraw money, while ensuring that the balance can only be modified through these methods, ensuring data integrity.
What is encapsulation in Python?
What is the purpose of using encapsulation?