You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何继承抽象类的子类未实现抽象方法仍可定义?

关于Python抽象类的疑问

我为理解抽象类特性编写了如下Python代码:

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,这符合预期。但为何子类Periodical继承Publication后未实现Description()仍可被定义?


解答

这是因为**Periodical会被Python自动识别为抽象类**——只要子类继承了抽象基类,但没有实现所有的抽象方法,这个子类就会成为抽象类,它本身不能被实例化,但定义这个类是完全允许的。

抽象类的核心作用之一就是作为中间层的基类,用来封装子类的公共逻辑(比如这里Periodical里的publisher属性和对应的初始化逻辑),然后让更下层的具体子类(比如Magazine、Newspaper)去实现父类的抽象方法。

你可以测试一下,如果尝试实例化Periodical:

p = Periodical("Test Periodical", "Test Publisher")

同样会抛出和Newspaper未实现方法时一样的TypeError,因为它本质还是抽象类,只有实现了所有抽象方法的子类才能被实例化。

内容的提问来源于stack exchange,提问作者Anumi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 17:24:29