Defining an Abstract Class in Python - Hands On
Defining an Abstract Class in Python
Defining an Abstract Class in Python
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`.
No Input
'Animal' is an abstract class 'say' is an abstract method 'Dog' is dervied from 'Animal' class Dog,'d1', says : I speak Booooo
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())
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())
'Animal' is an abstract class
'say' is an abstract method
'Dog' is dervied from 'Animal' class
Dog,'d1', says : I speak Booooo
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.
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.