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
248

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):
        self.title=title
        self.author=author  
    #Display method defined as Abstract
    @abstractmethod
    def display(): 
        pass

#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 
title=input()
author=input()
price=int(input())

#Object of MyBook class
new_novel=MyBook(title,author,price)

#Calling display method using object of MyBook class
new_novel.display()

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:

Share:

Author: Keerthana Buvaneshwaran