To Understand Encapsulation please do check out last post
Encapsulation is mechanism of bundling data (attribute) and methods that operate on that data within a single unit(class).

Encapsulation is like a medicine capsule: the outer shell hides the complex ingredient inside, delivering only the intended effect to your body. You don't need to know the chemical makeup to benefit from it.

Encapsulation is achieved through the use of access modifiers. Python primarily uses two types of access modifier.

  • Private: Accessible from anywhere.

  • Public: Accessible only within the class.

Similarly, in programming, encapsulation wraps data and methods in a class, exposing a simple, controlled interface while keeping the internal details private and secure.

class Car:
    def __init__(self,brand,model):
        self.brand=brand
        self.__model=model
        
    def get_brand(self):
        return self.__model+"!"
    def full_name(self):
        return f"{self.brand} {self.__model}"
        
my_car=Car("Tesla","X-Series")
print(my_car.__model)
Output:
ERROR!
Traceback (most recent call last):
  File "", line 12, in 
AttributeError: 'Car' object has no attribute '__model'
  1. Let say I want to make "model" attribute private so that nobody can manipulate the model name.
  2. So make it private just add '__model'

So, question arise if we can't access attribute but we can access function which include the private attribute.

class Car:
    def __init__(self,brand,model):
        self.brand=brand
        self.__model=model
        
    def get_brand(self):
        return self.__model+"!"
    def full_name(self):
        return f"{self.brand} {self.__model}"
        
my_car=Car("Tesla","X-Series")
print(my_car.full_name())
Output:
Tesla X-Series

Think of like if we have attribute which you don't want get manipulated then make it private.