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)
In [85]:
sciFiAmazing.price
Out[85]:
In [86]:
sciFiAmazing.display()
In [87]:
print(sciFiAmazing.title + " by " + sciFiAmazing.author)
print(sciFiAmazing)
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)
In [89]:
aBook = Book("Fight Club", "Forget Who", 7.5)
In [ ]: