python - Python中抽象类和接口(interface)的区别

标签 python interface abstract-class

Python中的抽象类和接口(interface)有什么区别?

最佳答案

您有时会看到以下内容:

class Abstract1:
    """Some description that tells you it's abstract,
    often listing the methods you're expected to supply."""

    def aMethod(self):
        raise NotImplementedError("Should have implemented this")

因为 Python 没有(也不需要)正式的接口(interface)契约,所以不存在抽象和接口(interface)之间的 Java 风格区别。如果有人努力定义一个正式的接口(interface),它也将是一个抽象类。唯一的区别在于文档字符串中声明的意图。

当你有鸭子打字时,抽象和接口(interface)之间的区别是一件令人毛骨悚然的事情。

Java 使用接口(interface)是因为它没有多重继承。

因为Python有多重继承,你也可能会看到这样的东西

class SomeAbstraction:
    pass  # lots of stuff - but missing something

class Mixin1:
    def something(self):
        pass  # one implementation

class Mixin2:
    def something(self):
        pass  # another

class Concrete1(SomeAbstraction, Mixin1):
    pass

class Concrete2(SomeAbstraction, Mixin2):
    pass

这使用一种带有混合的抽象父类(super class)来创建不相交的具体子类。

关于python - Python中抽象类和接口(interface)的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/372042/

相关文章:

java - 可选作为返回类型

c++ - 确保派生类具有适当类型的属性

c# - 简单基类和抽象类有什么区别?

python - 在 Python 3 中调用 pexpect 模块的 expect 方法时出现 TypeError

python - 无法在 python selenium 脚本中使用具有特殊字符 '$' 的密码

python - 如何增加两次而不出现列表索引超出范围的错误

python - 根据日期在 Python/Django 中过滤,忽略时间

flash - 如何在接口(interface)中公开方法而不将其公开给所有类

python - Ubuntu python : interface for running multiple script

java - 抽象类没有 arg 构造函数