Python中抽象类的实现 Hackerrank Day 13: Abstract Classes

感情迁移 提交于 2020-01-10 21:13:30
在抽象类中定义抽象方法,无需实现功能
子类继承抽象类,但是必须定义抽象方法的具体功能

Hackerrank Example Code

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 #########

#Write MyBook class
class MyBook(Book):
    def __init__(self,title,author,price):
        super().__init__(title,author) ########
        self.price=price
    def display(self): #######
        print('Title: '+self.title+'\nAuthor: '+self.author+'\nPrice: '+ str(self.price))


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

Sample Input

The following input from stdin is handled by the locked stub code in your editor:

The Alchemist
Paulo Coelho
248

Sample Output

The following output is printed by your display() method:

Title: The Alchemist
Author: Paulo Coelho
Price: 248
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!