理解Python中的抽象基类

2024-09-29 00:13:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读关于抽象基类的文章时,看到了https://www.python-course.eu/python3_abstract_classes.php网站。我对它们有大致的了解,但我发现两种说法互相矛盾

Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.

以及

A class that is derived from an abstract class cannot be instantiated unless all of its abstract methods are overridden.

我对第一条语句的理解是,派生类不需要实现父类的抽象方法,这是错误的。我做了一个样本程序来检查

from abc import ABC, abstractmethod

class AbstractClassExample(ABC):

    @abstractmethod
    def do_something(self):
        print("Some implementation!")

class AnotherSubclass(AbstractClassExample):

    def just_another_method(self):
        super().do_something()
        print("The enrichment from AnotherSubclass")

x = AnotherSubclass() # TypeError: Can't instantiate abstract class AnotherSubclass with abstract methods do_something
x.do_something()

我想解释一下第一句话的意思(最好是举例说明)


Tags: offromselfabstractandefdoare
1条回答
网友
1楼 · 发布于 2024-09-29 00:13:44

您的代码证明了第二条语句是正确的。这并不表明第一个陈述是错误的

在代码中,您试图实例化AnotherSubclass,这是不允许的,因为AnotherSubclass没有实现所有的抽象方法。第二种说法是这样的

但是,如果删除最后两行,即不实例化AnotherSubclass,那么在尝试运行代码时,代码不会产生错误。这表明第一条语句是正确的—允许存在未实现其所有抽象方法的抽象类的子类

您可以编写AnotherSubclass的另一个子类YetAnotherClass,这次实现了抽象方法,您将能够实例化YetAnotherClass。请注意,您的程序现在做了一些事情,AnotherSubclass仍然允许存在

相关问题 更多 >