w3resource

Python: What is encapsulation in OOP?

Python Encapsulation: Bundling data and methods in OOP

Encapsulation is one of the fundamental principles of object-oriented programming (OOP) and refers to the practice of bundling the data (attributes) and methods (functions) that operate on the data into a single unit, known as a class. The purpose is to hide the internal details of how a class works and provide a clear interface for interacting with it.

Encapsulation in Python is achieved through access modifiers, which control the visibility and accessibility of class members (attributes and methods). The three main access modifiers are:

  • Public (public): Members declared public are accessible from anywhere, both inside and outside the class. Unless explicitly marked as private, all Python members are public by default.
  • Protected (protected): Members declared as protected are accessible within the class and its subclasses. In order to declare a member protected, you can prefix its name with an underscore (_).
  • Private (private): Members that are declared as private are only accessible within the class. To declare a member as private, you can prefix its name with double underscores (__).

Here's a simple example to illustrate encapsulation:

Code:

class Bike:
    def __init__(self, make, model):
        self._make = make      # Protected attribute
        self.__model = model   # Private attribute
    
    def start_engine(self):
        print(f"{self._make} {self.__model} engine started")    
    def __drive(self):
        print(f"{self._make} {self.__model} is driving")
# Creating an instance of the Bike class
my_bike = Bike("Harley-Davidson", "Iron 883")
# Accessing public method
my_bike.start_engine()
# Accessing protected attribute
print(my_bike._make)
# Accessing private attribute 
print(my_bike._Bike__model)  

Output:

Harley-Davidson Iron 883 engine started
Harley-Davidson
Iron 883

In the example above, 'make' is a protected attribute, and _model is a private attribute. The start_engine method is a public method, and the __drive method is a private method. Although Python does not strictly enforce access restrictions like some other languages, it uses underscores to indicate visibility and accessibility for class members.



Follow us on Facebook and Twitter for latest update.