【问题标题】:Why can I instantiate an abstract class without implementing an abstractmethod?为什么我可以在不实现抽象方法的情况下实例化抽象类?
【发布时间】: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


【解决方案1】:

您不需要在子类中提供抽象方法的具体实现。不这样做的子类本身仍然是一个抽象基类。

只有当您尝试实例化一个类时,才会检查未被覆盖的抽象方法。如果有,则实例化失败。您不能直接实例化Periodical,但该类本身只是另一个抽象基类,其子类BookMagazineNewspaper 通过实现Description 变得具体。

# Class is defined...
>>> Periodical
<class '__main__.Periodical'>

# ... but you can't instantiate it
>>> Periodical()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Periodical with abstract method Description

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2014-07-12
    • 2015-10-06
    • 2019-02-11
    • 2013-03-07
    • 2017-02-05
    相关资源
    最近更新 更多