An Abstract Base Class or ABC mandates the derived classes to implement specific
methods from the base class.
It is not possible to create an object from a defined ABC class.
Creating objects of derived classes is possible only when derived classes override
existing functionality of all abstract methods defined in an ABC class.
ABC - Example
In Python, an Abstract Base Class can be created using module abc.
Example 1
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
In Example 1, Abstract base class Shape is defined with two abstract methods area
and perimeter.
ABC - Example...
Example 1...
With existing abstract class definition of Shape, if you try creating a Shape
object it results in TypeError.
s1 = Shape()
Output
TypeError: Can't instantiate abstract class Shape with abstract methods area,
perimeter
ABC - Example...
Example 1...
class Circle(Shape):
def __init__(self, radius):
self.__radius = radius
@staticmethod
def square(x):
return x**2
def area(self):
return 3.14*self.square(self.__radius)
c1 = Circle(3.9)
Creating object c1, with out definingperimeter inside derived class, Circle,
resulted in TypeError.
Output
TypeError: Can't instantiate abstract class Circle with abstract methods perimeter
ABC - Example...
Example 1...
Corrected class definition of Circle, that contains perimeter definition too.
class Circle(Shape):
def __init__(self, radius):
self.__radius = radius
@staticmethod
def square(x):
return x**2
def area(self):
return 3.14*self.square(self.__radius)
def perimeter(self):
return 2*3.14*self.__radius
c1 = Circle(3.9)
print(c1.area())
Output
47.7594
Q1
import inspect
from abc import ABC, abstractmethod
# Define the abstract class 'Animal' below
# with abstract method 'say'
class Animal(ABC):
@abstractmethod
def say(self):
pass
# Define class Dog derived from Animal
# Also define 'say' method inside 'Dog' class
class Dog(Animal):
def say(self):
return 'I speak Booooo'
if __name__ == '__main__':
if issubclass(Animal, ABC):
print("'Animal' is an abstract class" )
if '@abstractmethod' in inspect.getsource(Animal.say):
print("'say' is an abstract method")
if issubclass(Dog, Animal):
print("'Dog' is dervied from 'Animal' class" )
d1 = Dog()
print("Dog,'d1', says :", d1.say())