Py17: Abstraction

Abstraction basic implementation of a function is hidden from user. The user can only view basic functionalities while its internal details are hidden.

Abstraction can be achieved by using abstract class. An abstract class consist of at least one abstract method and concrete method. Concrete methods are what we normally write, it has implementation, but an abstract method do not have implementation.

def abstract_method_name(self):
    pass

Abstract class are considered as checklist for its subclass to makes sure a set of methods are implemented. Abstract classes are inherited by a subclass and the abstract methods are implemented there.

By creating abstract class we are actually creating API (Application Program Interface). These can be used by third party to provide implementation and help work in large teams

In python, we need to import ABC class from abc module to use abstraction concept.

from abc import ABC

class AbstractClassName(ABC):
    # codes

ABC stands for Abstract Base Class. We use a decorator @abstractmethod to define a method as abstract method. These decorator ensures an implementation is given by subclass, otherwise an error is invoked while compiling. So we need to import the decorator as well.

from abc import ABC, abstractmethod

class AbstractClassName(ABC):
    # codes

For example,

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def sides(self):
        pass

class Triangle(Shape):
    def sides(self):
        print("Triangle has three sides")

class Square(Shape):
    def sides(self):
        print("Square has four sides")

tri = Triangle()
squ = Square()

tri.sides()
squ.sides()

Output

Triangle has three sides
Square has four sides

Abstract class cannot be instantiated, they can be implemented only by its subclass.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def sides(self):
        pass

class Triangle(Shape):
    def sides(self):
        print("Triangle has three sides")

class Square(Shape):
    def sides(self):
        print("Square has four sides")

sh = Shape()

Output

Traceback (most recent call last):
  File "/media/civa/CIVA16GB/whiteboard/Python/src_example/abstraction/example1.py", line 16, in <module>
    sh = Shape()
TypeError: Can't instantiate abstract class Shape with abstract method sides

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net