Home / Programs / Defining an Abstract Class in Python - Hands On
🚀 Programming Example

Defining an Abstract Class in Python - Hands On

👁 316 Views
💻 Practical Program
📘 Step Learning

Defining an Abstract Class in Python

📌 Information & Algorithm

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 Code

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

🖥 Program Output

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

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.