Python- Encapsulation Vs Abstraction

In this tutorial you will master everything about the OOPs concept of encapsulation and abstraction in python and how they differ from each other. Also you will walk through the important access modifiers in object oriented programming such as  private ,public and protected in detail with examples.

In your previous tutorial you have grasped the concept of inheritance in python. If you are new to OOPS , we would suggest you to learn our tutorial of inheritance to acquaint yourself with OOPS.

What Is Encapsulation

Encapsulation is one of the important building blocks of object oriented programming (OOP) which enables the wrapping of all data (attributes and methods) into a single component(class) thereby preventing the accidental modification of data by imposing some restrictions on accessing variables or methods directly.

Encapsulation

Encapsulation

The figure gives you the idea that a class is an example of encapsulation which encapsulates all its data , i.e attributes and methods.

In a real world context, consider your house as an application which consists of bedrooms,dining room , kitchen etc that can be viewed as classes. Based on the functionality you keep different items(data) in different parts(classes) of your house like Bed in bedroom, dining table in dining room, stove in kitchen. This is encapsulation in real life.

Encapsulation is often referred to as Data hiding as it bestows a mechanism of access control. So what is data hiding? Data hiding is the process of hiding the data of an entity from others so as to prevent the accidental modification of data by other entities.

Consider the scenario of keeping valuable items like money and jewellery in your house. Practically we keep them in a locker hiding from the external entities. So is the data hiding in programming.

How Data Hiding Is Performed

Access modifiers are inevitable elements of object oriented programming  as they restrain the access to the attributes and methods in a class.Python does not have specific access modifiers unlike C , Java etc. Python being an object oriented programming language makes use of underscore to perform the function of access modifiers that are done in other languages.

In python , the encapsulation approach is a bit different. Based on the visibility of the object’s attribute in a class,the attributes are classified in two.They are private and public. If a data member or member function is accessible from any part of the program it is considered as public while if its visibility is restricted to the defined class then it is considered as private. Any data or member function that prefixes with double underscore is private to that class.

The following example will give you a clear picture on encapsulation.

class Access:

    def __init__(self):

        #public attribute
        self.name= input('Enter your name :')

        #private attribute
        self.__secretcode=input("Enter your secret code :")          

    def permit(self):
        if self.name =='abc' and self.__secretcode =='123!':
         print("Access Granted" )
        else:
         print('Access Denied')

ob = Access()
ob.permit()

print(ob.name)     #public attribute is visible to external world
print(ob._secretcode)  #private attribute is invisible to external world 

This example is a simplistic form of the login validation. Here, the attribute name is represented as public while attribute secretcode is private. You can see that the permit() method checks if the name and secretcode satisfies the condition or not.If the condition is met then an Access granted message is printed, otherwise the access denied message is printed .This shows the backend process of login. Later if you try to retrieve the attibutes name and secret code using the object of the class, you will get the name whereas the secret code gives you an error.

Here is the output of the example:

Enter your name :abc
Enter your secret code :123!
Access Granted

abc
Traceback (most recent call last):
  File "oops_ex.py", line 211, in 
    print(ob._secretcode)
AttributeError: 'Access' object has no attribute '_secretcode'

OR

Enter your name :klm
Enter your secret code :1234
Access Denied

klm
Traceback (most recent call last):
  File "oops_ex.py", line 211, in 
    print(ob._secretcode)
AttributeError: 'Access' object has no attribute '_secretcode' 

Observing the output you have noted that in both cases,when you try to access __secretcode attribute externally, an AttributeError saying __secretcode does not exist. This is accomplished by a process named name mangling in which all private attributes are masked internally by affixing the class name before them. For instance, attribute __secretcode would internally become _Access__secretcode.Thus hiding the secret code from the outside world and enabling data hiding.

You will get these private attributes by running dir() as shown in the below example.

print(dir(ob))
['_Access__secretcode', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'permit']

This gives the possibility of accessing such private attributes as object._classname__privateattributename.Changing the last line of above program gives you the following output:

print(ob.name)     #public attribute is visible to external world
print(ob._Access__secretcode) #private attribute is invisible to external world 

Output:

Enter your name :abc
Enter your secret code :123!
Access Granted
abc
123!

What Is Abstraction

Like encapsulation,Abstraction is one of the basic building blocks of Object oriented programming.

Abstraction is the process of hiding internal implementation of a process from its end user,showing only essential features of data to the external world in order to reduce complexity and increase efficiency. In the context of programming, isolating the signature of a method from its definition is known as abstraction.It generally focuses on ideas rather than the functionality.

In our daily life, we use appliances like TV, Refrigerator, Washing Machine etc to meet some specific needs. We are not aware of its internal working or we are not interested to know about. We just operate them, profoundly their internal implementation is abstracted from us.

How abstraction can be achieved

Python abstraction can be achieved through the use of abstract classes and methods in programs .So what is an abstract class and abstract method in python?

How abstraction can be achieved

How abstraction can be achieved

An abstract class is a class which contains one or more abstract methods.A class becomes an abstract class if and only if it contains at least one abstract method. A method is said to be an abstract method if it is declared but not defined.Specifically, an abstract method does not contain any implementation.However,all the implementation can be defined inside the methods of child classes which inherits the abstract class.

Another point to be noted is that by default python does not support any abstract class but we can achieve it by importing a class named ABC(Abstract Base Class) from the module abc. The syntax to create an abstract class is as follows.

from abc import ABC
class class_name(ABC): 

Let's check out the following example to understand the concept of abstraction in the technical world.

from abc import ABC

class Shape(ABC):         #abstract class
    def area_calc(self):  #abstract method
        pass 

This shows the creation of an abstract class. Here Shape is the abstract class with abstract method area_calc(). area_calc() method is not defined here instead we use the pass statement. So this method is declared but not defined. What would happen if we try to create an object for the abstract class. See below example:

from abc import ABC

class Shape(ABC):         #abstract class
    def area_calc(self):  #abstract method
        pass

ob = Shape() 

Output Error:

Traceback (most recent call last):
  File "oops_ex.py", line 225, in 
    ob = Shape()
TypeError: Can't instantiate abstract class Shape with abstract methods area_calc

Now let's add the child class Rect which inherits the abstract class shape.What would happen if the implementation is not defined inside the method of a child class.

from abc import ABC

class Shape(ABC):         #abstract class
    def area_calc(self):  #abstract method
        pass

class Rect(Shape):
        pass
obr = Rect() 

Output Error:

Traceback (most recent call last):
  File "oops_ex.py", line 226, in 
    obr = Rect()
TypeError: Can't instantiate abstract class Rect with abstract methods area_calc

You will receive a TypeError saying we cannot instantiate class Rect . So this is an impulsion to define the method as Rect is a child class which inherits the abstract class. All the implementation can be defined inside the method area_calc() of the Rect class. Observe the example carefully and learn how abstraction works.

from abc import ABC

class Shape(ABC):         #abstract class
    def area_calc(self):  #abstract method
        pass
class Rect(Shape):
    l=float(input('Enter length :'))
    b=float(input('Enter breadth :'))
    def area_calc(self):
        return(self.l*self.b)
obr = Rect()

print("Area of Rectangle is ",obr.area_calc()) 

Output:

Enter length :10
Enter breadth :20
Area of Rectangle is  200.0

The key takeaways is that an abstract class holds normal methods along with abstract methods and we cannot instantiate any abstract class.

Abstraction Vs Encapsulation

Abstraction and encapsulation are analogous since abstraction of data can be achieved through encapsulation. Even though both abstraction and encapsulation go hand in hand, they are very much different from each other.

Abstraction Encapsulation
Abstraction hides unnecessary data and shows relevant data to the end user. Encapsulation encapsulates data and code from the external world to circumvent the misuse.
Abstraction works on the design level Encapsulation works on the application level
Abstraction focuses on the idea of the program. Encapsulation focuses on functionality or implementation of the code.
Focuses on what should be done Focuses on how it  should be done
Abstraction achieved by using abstract classes and abstract methods Encapsulation uses underscore as access modifiers to secure the codes by external entities