Encapsulation

Encapsulation is one of the fundamental concepts of object-oriented programming (OOP). It is a way of hiding the implementation details of an object from the outside world and making the object's internal state accessible only through a well-defined interface.

In Python, encapsulation is achieved through the use of access modifiers. There are three access modifiers in Python:

  1. Public: This is the default access level in Python. Public members can be accessed from anywhere, inside or outside the class.
  2. Protected: Protected members are denoted by a single underscore (_) prefix. They can be accessed only within the class and its subclasses.
  3. Private: Private members are denoted by a double underscore (__) prefix. They can be accessed only within the class.

Let's look at an example:


            class Car:
                def __init__(self, make, model, year):
                    self._make = make
                    self._model = model
                    self.__year = year

                def get_make(self):
                    return self._make

                def get_model(self):
                    return self._model

                def get_year(self):
                    return self.__year

            my_car = Car("Ford", "Mustang", 2022)

            print(my_car.get_make())    # Output: Ford
            print(my_car.get_model())   # Output: Mustang
            print(my_car.get_year())    # Output: 2022
            print(my_car.__year)        # Output: AttributeError: 'Car' object has no attribute '__year'
        

In the above example, we have defined a Car class with three attributes: make, model, and year. The make and model attributes are defined as protected members with a single underscore prefix, while the year attribute is defined as a private member with a double underscore prefix.

To access the protected and private members of the Car class, we have defined getter methods. The get_make() and get_model() methods return the values of the make and model attributes, respectively. The get_year() method returns the value of the year attribute.

When we create an instance of the Car class and try to access its private member __year directly, we get an AttributeError because private members cannot be accessed from outside the class.

Conclusion

Encapsulation is an important concept in OOP because it allows for better code organization, maintainability, and security. By hiding the implementation details of an object, we can prevent unauthorized access to its internal state and make the code easier to understand and modify.