【发布时间】:2022-07-22 23:18:15
【问题描述】:
为了理解抽象类,我创建了一个简单的模型:
from abc import ABC, abstractmethod
class Publication(ABC):
def __init__(self, title):
self.title = title
@abstractmethod
def Description(self):
pass
class Periodical(Publication):
def __init__(self, title, publisher):
super().__init__(title)
self.publisher = publisher
class Book(Publication):
def __init__(self, title, author):
super().__init__(title)
self.author = author
def Description(self):
print(f'Book: {self.title} ({self.author})')
class Magazine(Periodical):
def __init__(self, title, publisher):
super().__init__(title, publisher)
def Description(self):
print(f'Magazine: {self.title} ({self.publisher})')
class Newspaper(Periodical):
def __init__(self, title, publisher):
super().__init__(title, publisher)
def Description(self):
print(f'Newspaper: {self.title} ({self.publisher})')
book = Book('Thoughts', 'A. Einstein')
magazine = Magazine('Sailing', 'M. Polo')
newspaper = Newspaper('Daily Joke', 'Ms. Maisel')
book.Description()
magazine.Description()
newspaper.Description()
在Publication 中,我将Description() 定义为抽象方法。如果我不实施它,例如在Newspaper 类中,抛出错误:TypeError: Can't instantiate abstract class Newspaper with abstract method Description。这就是我的意图。
但是为什么不实现Description()就可以从Publication创建Periodical呢?
【问题讨论】:
-
你不能这样做,你的代码也不会尝试。
标签: python class abstract-class