Python Tutorial: Encapsulation 🎯

beginner
13 min

Python Tutorial: Encapsulation 🎯

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.

Understanding Encapsulation 📝

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.

Classes and Objects 💡

  • A class is a blueprint for creating objects. It defines a set of properties (variables) and methods (functions) that are associated with those properties.
python
class MyClass: def __init__(self, name): # Constructor self.name = name
  • Creating an object (instance) from a class:
python
my_obj = MyClass("John Doe")

Access Modifiers 📝

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.

  • Public variables (no leading underscores) can be accessed from anywhere:
python
class MyClass: public_var = "I'm public"
  • Private variables (leading double underscores) are only accessible within the class:
python
class MyClass: def __init__(self): self.__private_var = "I'm private" def display_private(self): print(self.__private_var)

Methods 💡

Methods are functions that are defined within a class. They are used to perform actions on the class's data.

python
class MyClass: def greet(self): print(f"Hello, {self.name}!") my_obj.greet() # Output: Hello, John Doe!

Encapsulation in Action 💡

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:

  • Keep data and methods related to that data together, making the code more organized and easier to understand.
  • Control access to data, preventing unauthorized access and ensuring data integrity.
  • Make it easier to change the implementation of a class without affecting other parts of the code.

Practical Example 🎯

Let's create a BankAccount class that encapsulates a bank account's balance and methods for depositing and withdrawing money:

python
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: 1300

In 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.

Encapsulation Quiz 📝

Quick Quiz
Question 1 of 1

What is encapsulation in Python?

Quick Quiz
Question 1 of 1

What is the purpose of using encapsulation?