HackerRank Day 13 Solution in Python: Abstract Classes

Today we will see the HackerRank Day 13 Solution in Python. The problem is named Abstract Classes which is part of 30 Days of code on HackerRank. Let’s get started!

Day 13: Abstract Classes Problem statement

We are given a Book class and a Solution class, our task is to write a MyBook class that inherits from the Book class. It should have a parameterized constructor and implements the abstract display() method of the Book class

Sample Input

The Alchemist
Paulo Coelho

Sample Output

Title: The Alchemist
Author: Paulo Coelho
Price: 248

You can solve the problem here.

HackerRank Day 13 Solution in Python

from abc import ABCMeta, abstractmethod

#Base class
class Book(object, metaclass=ABCMeta):
    #Constructor of Book class
    def __init__(self,title,author):
    #Display method defined as Abstract
    def display(): 

#MyBook class inherited from Book class
class MyBook(Book):
    def __init__(self, title, author, price):
        super().__init__(title, author)
        self.price = price
    #Display method to print the book details
    def display(obj):
        print("Title:", obj.title)
        print("Author:", obj.author)
        print("Price:", obj.price)

#Getting book details as user inputs 

#Object of MyBook class

#Calling display method using object of MyBook class

Code Explanation:

  • We created a MyBook class which is inherited from the Book class.
  • Then we defined the constructor with parameters title, author, price
  • After that, the method display is created which prints the details of the book.

Also Read:

Avatar of Keerthana Buvaneshwaran

Author: Keerthana Buvaneshwaran