Characteristics of Object Oriented programming in Python Part-6

In part-5 of this segment we discussed Polymorphism. In this article we’ll discuss Abstraction and its implementation in Python

Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our example, Human Being’s can talk, walk, hear, eat, but the details are hidden from the outside world. We can take our skin as the Abstraction factor in our case, hiding the inside mechanism.

 The terms encapsulation and abstraction (also data hiding) are often used as synonyms. They are nearly synonymous, i.e. abstraction is achieved through encapsulation. Data hiding and encapsulation are the same concept, so it’s correct to use them as synonyms. 

Confusion in Encapsulation and Abstraction often leads to implementation of these two concepts. For example:

class AbstractClass:

def do_somthing(self):
pass

class B(AbstractClass):
pass


a=AbstractClass()
b = B()

Above example is WRONG for the following reasons:

1. We can instantiate an object for AbstractClass hence it not an Abstract class.
2. We should not be able to instantiate objects of abstract classes.
3. We should be forced to implement do_something method in derived class B.

Hence, for the above reasons above example is wrong. Correct way of implementing Abstraction under Python is as , following:

  1. We have to use Python’s inbuilt module like this –
    from abc import ABC, abstractmethod
  2.  We need to import like above before making abstract classes
  3.  After that give ABC as an argument to class definition to make it abstract.

CORRECT Code:

from abc import ABC, abstractmethod

class AbstractBaseClass(ABC):

def __init__(self,value):
super().__init__()
self.value = value

@abstractmethod
def do_something(self,value):
pass

#derive from above class to make abstraction in Python
class dABC(AbstractBaseClass):

def do_something(self,value):
print("doing something %r" %value)

x = dABC(4)
x.do_something(9)

Leave a Reply