您有时会看到以下内容:
class Abstract1( object ):
"""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风格的区别不存在。如果有人努力定义一个正式接口,那么它也将是一个抽象类。唯一的区别是docstring中声明的意图。在
当你使用duck类型时,抽象和接口之间的区别是一件非常棘手的事情
Java使用接口是因为它没有多重继承
因为Python具有多重继承,您可能还会看到类似这样的情况
class SomeAbstraction( object ):
pass # lots of stuff - but missing something
class Mixin1( object ):
def something( self ):
pass # one implementation
class Mixin2( object ):
def something( self ):
pass # another
class Concrete1( SomeAbstraction, Mixin1 ):
pass
class Concrete2( SomeAbstraction, Mixin2 ):
pass
这使用一种带有mixin的抽象超类来创建不相交的具体子类