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/