Python 3.6 [PY36 env]

Abstract Object Coding Exmple

This code example comes from a problem provided on www.hackerrank.com (python 30 day challenge). This syntax was created/tested on Python 3.6.


In [83]:
# tested on Python 3.6 ... 
# comments help explain some conceptual things about this code

from abc import ABCMeta, abstractmethod

class Book(object, metaclass=ABCMeta):     # sets up abstract class
    def __init__(self,title,author):       # abstract classes can be subclassed
        self.title=title                   # but cannot be instantiated
        self.author=author  
        print("Creating Book: ", self.title, "by", self.author)
        
    @abstractmethod                        # abstract method definition in Python
    def display(): pass                    # abstract method definition in Python continued
    
    @abstractmethod 
    def strSummary(): pass
    
    def __str__(self):
        return self.title + " by " + self.author

class MyBook(Book):                                     # if this class adds any abstract methods
    def __init__(self, title, author, price):           # it would be abstract too
        super().__init__(title, author)                 # to be a concrete class that can be instantiated
        # Book.__init__(self, title,author)             # it must implement all inherited abstract methods
        self.price = price                              # note: Book. and super() solutions both work
        print("Creating MyBook: ", self.price)          #       but super() is a best practice for forward compatibility 
                                                        # 
    def strSummary(self):
        return ((" Title: %s\n" %self.title) +
                ("Author: %s\n" %self.author) + 
                (" Price: %s" %self.price))
    
    def display(self):
        print(self.strSummary())

#         print("Title: %s" %self.title)
#         print("Author: %s" %self.author)
#         print("Price: %d" %self.price)

In [84]:
sciFiAmazing = MyBook("The Lord of the Rings", "J.R.R. Tolkien", 8.5)


Creating Book:  The Lord of the Rings by J.R.R. Tolkien
Creating MyBook:  8.5

In [85]:
sciFiAmazing.price


Out[85]:
8.5

In [86]:
sciFiAmazing.display()


 Title: The Lord of the Rings
Author: J.R.R. Tolkien
 Price: 8.5

In [87]:
print(sciFiAmazing.title + " by " + sciFiAmazing.author)
print(sciFiAmazing)


The Lord of the Rings by J.R.R. Tolkien
The Lord of the Rings by J.R.R. Tolkien

In [88]:
# note ... abstract class cannot be instantiated
# this will throw an error as shown here:

try:
    aBook = Book("Fight Club", "Forget Who", 7.5)
except Exception as ee:
    print(type(ee))
    print(ee)


<class 'TypeError'>
Can't instantiate abstract class Book with abstract methods display, strSummary

In [89]:
aBook = Book("Fight Club", "Forget Who", 7.5)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-1cd5a848b450> in <module>()
----> 1 aBook = Book("Fight Club", "Forget Who", 7.5)

TypeError: Can't instantiate abstract class Book with abstract methods display, strSummary

In [ ]: