我一直在项目中使用抽象类,意识到我并没有完成有意义的事情。
对于某些抽象模型:
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方式使用抽象类和方法?