Python中抽象类和接口的区别

Python中抽象类和接口的区别

问题描述:

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

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

您有时会看到以下内容:

What you'll see sometimes is the following:

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 风格的区别不存在.如果有人努力定义一个正式的接口,它也将是一个抽象类.唯一的区别在于文档字符串中声明的意图.

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:
    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的抽象超类来创建不相交的具体子类.

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