您有时会看到以下内容:
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没有(也不需要)正式的接口契约,所以抽象和接口之间不存在Java风格的区别.如果有人努力定义一个正式的接口,它也将是一个抽象类.唯一的区别在于文档字符串中声明的意图.
抽象和界面之间的区别是一个令人毛骨悚然的事情,当你有鸭子打字.
Java使用接口是因为它没有多重继承.
由于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
它使用一种带有mixin的抽象超类来创建不相交的具体子类.