DAY 13: Abstract Classes

idimaimuna profile image M__ ・1 min read

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):
    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}')


Sample Input:
The Alchemist
Paulo Coelho

Sample Output:
Title: The Alchemist
Author: Paulo Coelho
Price: 248

Posted on by:

idimaimuna profile



New programmer interested in web development and python as well. Aspiring to learn and be better than I started.


markdown guide