Python中抽象类和接口的区别

Python中抽象类和接口的区别

问题描述:

Python中抽象类和接口有什么区别?

What is the difference between abstract class and interface in Python?

您有时会看到以下内容:

What you'll see sometimes is the following:

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中声明的意图。

Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.

抽象和接口之间的区别是当你打字时打字的东西。

And the difference between abstract and interface is a hairsplitting thing when you have duck typing.

Java使用接口因为它没有多重继承。

Java uses interfaces because it doesn't have multiple inheritance.

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

Because Python has multiple inheritance, you may also see something like this

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

这使用一种带有mixins的抽象超类来创建不相交的具体子类。

This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.