Defining an Abstract Class in Python - Hands On

Python / Abstraction and Encapsulation

681

1. Defining an Abstract Class in Python

• Define an abstract class Animal, with an abstract method `say`.

Hint: Use 'abc' module.

• Define a child class 'Dog`, derived from `Animal. Also, define a method 'say' which prints the message 'I speak Booooo`.

Given Input:

No Input

Expected Output:

'Animal' is an abstract class
'say' is an abstract method
'Dog' is dervied from 'Animal' class
Dog,'d1', says : I speak Booooo

Hints Code:

import inspect

from abc import ABC, abstractmethod

# Define the abstract class 'Animal' below
# with abstract method 'say'
class Animal

# Define class Dog derived from Animal
# Also define 'say' method inside 'Dog' class
class Dog

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())

Program:

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())

Output:

'Animal' is an abstract class
'say' is an abstract method
'Dog' is dervied from 'Animal' class
Dog,'d1', says : I speak Booooo

This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.