Introduction

Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP) in Python. It involves the concept of data hiding, which restricts access to an object's internal data, allowing controlled and safe interaction with the object's attributes and methods. In this guide, we'll explore the concept of encapsulation and data hiding in Python, along with sample code.


What Is Encapsulation?

Encapsulation is a concept that bundles data and the methods that operate on that data into a single unit, known as a class. It hides the internal details of how data is stored and processed, providing an interface for external code to interact with the class.


Data Hiding with Access Modifiers

In Python, data hiding is implemented using access modifiers. There are three types of access modifiers:

  • Public: No access modifier is used. Members are accessible from outside the class.
  • Protected: Members are indicated by a single underscore (e.g., _variable). They are intended to be protected, but access is still possible.
  • Private: Members are indicated by a double underscore (e.g., __variable). They are considered private and should not be accessed directly from outside the class.

Using Access Modifiers

You can use access modifiers to control the visibility and access of class members. Here's an example of a class with public, protected, and private attributes:

class Employee:
def __init__(self, name, salary):
self.name = name # Public attribute
self._salary = salary # Protected attribute
self.__id = 101 # Private attribute
def display_info(self):
return f"Name: {self.name}, Salary: {self._salary}, ID: {self.__id}"

Accessing Members with Encapsulation

With encapsulation, you can access members through the methods provided by the class. This ensures that data is accessed and modified in a controlled and validated manner.

# Creating an object
employee = Employee("Alice", 50000)
# Accessing and modifying data through methods
employee.name = "Bob" # Accessing a public attribute directly
employee._salary = 60000 # Accessing a protected attribute directly
# employee.__id = 102 # Accessing a private attribute directly (results in an error)
# Accessing data through methods
info = employee.display_info()
print(info)

Conclusion

Encapsulation and data hiding play a crucial role in OOP by ensuring that data is protected and accessed in a controlled manner. By using access modifiers, you can define the level of visibility for class members, promoting code organization and security.