Python Encapsulation and Access Modifiers


Python Encapsulation

Python Encapsulation is the process of wrapping data and methods in a single unit. A class itself is an example of encapsulation, as it wraps data members and methods in a single unit.

Encapsulation
In [1]:
class Car:
    def __init__(self, car_type, seating_capacity):
        self.car_type = car_type
        self.seating_capacity = seating_capacity
        
    def car_details(self):
        print("This is a ", self.car_type, "with seating capacity of ", self.seating_capacity )
In [2]:
model_3 = Car("Sedan", 5)
In [3]:
model_3.car_details()
This is a  Sedan with seating capacity of  5

Advantages of Encapsulation

1. Data Hiding:

Encapsulation helps in hiding the internal details of a class from the outside world. It allows you to make certain attributes or methods private or protected, preventing direct access from outside the class. This ensures that the implementation details are not exposed to the external code, promoting a more robust and secure design.

2. Code Organization:

Encapsulation helps in more organized code structure. Grouping related data and behavior into a class makes it easier to understand and maintain the code.

3. Code Reusability:

Encapsulation facilitates code reuse by encapsulating related functionality into a class. Once a class is defined, it can be instantiated and reused in different parts of the program.

4. Enhanced Security:

By restricting direct access to certain attributes and methods, encapsulation helps in creating a protective barrier around the data of a class. This prevents unintended modifications and enhances the overall security of the program.

5. Easy Debugging and Testing:

Encapsulation makes it easier to isolate and debug issues within a class. It also simplifies the testing process, as you can focus on testing the public interface of a class without worrying about its internal implementation details.

Access Modifiers

In Python, we have access modifiers to restrict the access of the variables and methods of the class. They actually control the visibility and accessibility of the class variables(attributes) and methods.

Python has three types of the access modifiers:

  1. Public Members
  2. Protected Members
  3. Private Members
Access Modifiers

Public Members

When no access modifier is specified with the variable and methods, then they are public by default. These are accessible from within the class and outside the class. No keyword is used by the public members.

In [1]:
class Car:
    def __init__(self, car_type, seating_capacity):
        self.car_type = car_type
        self.seating_capacity = seating_capacity
        
    def car_details(self):
        print("This is a ", self.car_type, "with seating capacity of ", self.seating_capacity )
In [2]:
model_3 = Car("Sedan", 5)
In [3]:
print(model_3.car_type)
Sedan
In [4]:
model_3.car_details()
This is a  Sedan with seating capacity of  5

Protected Members

These are accessible from within the class and also from its subclasses.

To make any member protected, we add a single underscore as the prefix of the variable name.

In [1]:
class car:
    def __init__(self, car_type, cost):
        self.car_type = car_type
        self._cost = cost
        """
    def car_details(self):
        print("This is a", self.car_type, ".")
        
    def car_cost(self):
        print("It's cost is",self._cost)
        """
class electric_sedan(car):
    def __init__(self, engine_type, car_type, cost):
        self.engine_type = engine_type
        car.__init__(self,  car_type, cost)
        
    def car_details(self):
        print("This is a", self.engine_type, "car and costs",self._cost)
        

e_car = electric_sedan("Electric", "Sedan", 25000)
e_car.car_details()
This is a Electric car and costs 25000

Private Members

These are accessible from within the class only. Even objects of the class cannot access them.

To make any member private, we add two underscores as the prefix of the variable names.

In [1]:
class Car:
    def __init__(self, car_type, cost):
        self.car_type = car_type
        self.__cost = cost
        
    def car_details(self):
        print("This is a", self.car_type, ".")
        
    def car_cost(self):
        print("It's cost is",self.__cost)
In [2]:
model_3 = Car("Sedan", 25000)
In [3]:
model_3.__cost
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-eb7dcd7d10e4> in <module>
----> 1 model_3.__cost

AttributeError: 'Car' object has no attribute '__cost'
In [4]:
model_3.car_cost()
It's cost is 25000

Access Modifiers Summary

Access Modifiers

References

  1. Access Modifiers in Python