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

在抽象类中定义抽象方法,无需实现功能
子类继承抽象类,但是必须定义抽象方法的具体功能

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
发布了128 篇原创文章 · 获赞 90 · 访问量 4870

猜你喜欢

转载自blog.csdn.net/weixin_45405128/article/details/103928628
今日推荐