什么时候使用Pythonic使用抽象类+抽象方法?

时间:2018-10-06 09:39:17

标签: python abstract-class abstract abstract-methods

我一直在项目中使用抽象类,意识到我并没有完成有意义的事情。

对于某些抽象模型:

class AbstractBar(metaclass=ABCMeta):
    ...
    @abstractmethod
    def foo(self, x):
       ''' Useful docstring '''

由课程实施:

class Bar(AbstractBar):
    ...
    def foo(self, x):
        ...

并按以下方式调用:

bar = Bar(...)
bar.foo(x)

如果Bar不管继承如何都没有实现foo,我会收到一个运行时错误,因此它无助于较早地捕获错误。

>
# Without inheritance
AttributeError: type object 'Bar' has no attribute 'foo'
# With inheritance
TypeError: Can't instantiate abstract class Bar with abstract methods foo

PEP 3119中引入抽象类时,它们被证明是一种检查issubclass()和isinstance()的方法,但后来尝试寻求宽恕似乎更具有Python风格。

我的问题是如何以Python方式使用抽象类和方法?

0 个答案:

没有答案