DEV Community

M__
M__

Posted on

DAY 13: Abstract Classes

The challenge was a continuation of classes just that it was dealing with abstract classes. Abstract classes are classes that have functions which have no body in them in simple terms, the functions are declared in that class but its functionality is not defined there and for the function to be executed, the derived class has to define its functionality.

Python uses the ABCMeta class for defining abstract base classes and it has a decorator, @abstractmethod to indicate when there is an abstract method.

The Task:
Given a Book class and a Solution class, write a MyBook class that does the following:
• Inherits from Book
• Has a parameterized constructor taking these parameters:

  1. string title
  2. string author
  3. int price • Implements the Book*class' abstract **display()* method so it prints these lines:
  4. Title: , a space, and then the current instance's title.
  5. Author: , a space, and then the current instance's author.
  6. Price:, a space, and then the current instance's price.
from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
    def __init__(self,title,author):
        self.title=title
        self.author=author   
    @abstractmethod
    def display(): pass


class MyBook(Book):
    def __init__(self, title, author, price):
        self.title = title
        self.author = author
        self.price = price

    def display(self):
        print(f'Title: {self.title}')
        print(f'Author: {self.author}')
        print(f'Price: {self.price}')


title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()

'''
Sample Input:
The Alchemist
Paulo Coelho
248

Sample Output:
Title: The Alchemist
Author: Paulo Coelho
Price: 248
'''
Enter fullscreen mode Exit fullscreen mode

Top comments (0)