Pages

Thursday 23 March 2023

Encapsulation in Python

Indtroduction

Encapsulation is one of the fundamental concepts of object-oriented programming (OOP). It refers to the practice of bundling data and methods that operate on that data into a single unit, which we call a class. Encapsulation helps us to hide the implementation details of a class from the outside world and make the code more robust, secure, and maintainable.


Encapsulation has two main benefits:


Security: 

Encapsulation provides security by preventing direct access to the data of a class. This means that the data is protected from accidental modification or tampering, which can cause errors or crashes in the program.


Abstraction:

Encapsulation provides abstraction by separating the implementation details of a class from the interface that the class presents to the outside world. This means that the user of the class doesn't need to know how the class works internally, but only needs to know how to use its interface.


In Python, we can achieve encapsulation using access modifiers. An access modifier is a keyword that we use to control the access to a class attribute or method from outside the class. Python provides three types of access modifiers:


Public access modifier (+): 

A public access modifier is the default access modifier in Python. It means that any class, method, or variable declared without any access modifier will be considered public. Public members can be accessed from anywhere, inside or outside of the class. In Python, public members are denoted with no prefix or with a single underscore prefix.


Example:


class MyClass:

    def __init__(self, public_var, _private_var):

        self.public_var = public_var

        self._private_var = _private_var

    def public_method(self):

        print("This is a public method.")

def _private_method(self):

print("This is a private method.")

obj = MyClass("Public", "Private")

print(obj.public_var)  # Output: Public

obj.public_method()  # Output: This is a public method.


Protected access modifier (_): 

In Python, there is no built-in protected access modifier like other programming languages such as Java and C++. However, we can use a single underscore prefix before the variable name or method name to indicate that it is protected. Protected members can be accessed within the class or its subclasses only.


Example:


class MyClass:

         def __init__(self, public_var, _protected_var):

        self.public_var = public_var

        self._protected_var = _protected_var

    def public_method(self):

        print("This is a public method.")

    def _protected_method(self):

        print("This is a protected method.")

class MyChildClass(MyClass):

    def child_method(self):

        self._protected_method()

obj = MyChildClass("Public", "Protected")

print(obj.public_var)     # Output: Public

obj.public_method()   # Output: This is a public method.

obj.child_method()    # Output: This is a protected method.

Private access modifier (__)

In Python, there is no built-in private access modifier like other programming languages such as Java and C++. However, we can use a double underscore prefix before the variable name or method name to indicate that it is private. Private members can be accessed within the class only.


Example:


class MyClass:

    def __init__(self, public_var, __private_var):

self.public_var = public_var

self.__private_var = __private_var

    def public_method(self):

  print("This is a public method.")

    def __private_method(self):

   print("This is a private method.")

obj = MyClass("Public", "Private")

print(obj.public_var)     # Output: Public

obj.public_method()       # Output: This is a public method.

obj.__private_method()    # Error: AttributeError: 'MyClass' object has no attribute

Let's take an example to understand encapsulation in Python:


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 def set_make(self, make): self.__make = make def set_model(self, model): self.__model = model def set_year(self, year): self.__year = year

In the above example, we have defined a class named "Car" that has three private attributes: make, model, and year. We have also defined six methods: three getter methods to get the values of these attributes, and three setter methods to set the values of these attributes.


The getter methods are public methods that can be accessed from outside the class, while the setter methods are private methods that can only be accessed from within the class.


We can create an object of the Car class and access its attributes and methods as follows:


my_car = Car("Toyota", "Corolla", 2021) print(my_car.get_make()) # Output: Toyota print(my_car.get_model()) # Output: Corolla print(my_car.get_year()) # Output: 2021 my_car.set_make("Honda") my_car.set_model("Civic") my_car.set_year(2022) print(my_car.get_make()) # Output: Honda print(my_car.get_model()) # Output: Civic print(my_car.get_year()) # Output: 2022

In the above example, we have created an object of the Car class named "my_car" and initialized its attributes with values.We have then used the getter methods to retrieve the values of these attributes and the setter methods to set the new values of these attributes.


Encapsulation helps us to create secure and robust code by hiding the implementation details of a class from the outside world. It also helps us to maintain the code by providing a clear and concise interface to access the class attributes and methods.

Conclusion:

Encapsulation is an essential concept of OOP, and Python provides us with access modifiers to achieve it. By using access modifiers, we can create secure, robust, and maintainable code.

Please subscribe my youtube channel for latest python tutorials and this article

No comments:

Post a Comment