Python 中的抽象方法
我需要类似 Python (3.2) 中的 abstract protected
方法:
class Abstract:
def use_concrete_implementation(self):
print(self._concrete_method())
def _concrete_method(self):
raise NotImplementedError()
class Concrete(Abstract):
def _concrete_method(self):
return 2 * 3
定义一个“抽象”方法只是为了引发 NotImplementedError 实际上有用吗?
在抽象方法中使用下划线是否是一种好的风格,在其他语言中该方法会受到保护
?
抽象基类(abc)会改善什么吗?
I need something like an abstract protected
method in Python (3.2):
class Abstract:
def use_concrete_implementation(self):
print(self._concrete_method())
def _concrete_method(self):
raise NotImplementedError()
class Concrete(Abstract):
def _concrete_method(self):
return 2 * 3
Is it actually useful to define an "abstract" method only to raise a NotImplementedError?
Is it good style to use an underscore for abstract methods, that would be protected
in other languages?
Would an abstract base class (abc) improve anything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Python 中,通常避免使用此类抽象方法。您通过文档定义一个接口,并简单地假设传入的对象满足该接口(“鸭子类型”)。
如果您确实想使用抽象方法定义抽象基类,可以使用 < code>abc 模块:
同样,这不是通常的 Python 做事方式。
abc
模块的主要目标之一是引入一种重载isinstance()
的机制,但通常会避免isinstance()
检查支持鸭子打字。如果需要,可以使用它,但不能作为定义接口的通用模式。In Python, you usually avoid having such abstract methods alltogether. You define an interface by the documentation, and simply assume the objects that are passed in fulfil that interface ("duck typing").
If you really want to define an abstract base class with abstract methods, this can be done using the
abc
module:Again, that is not the usual Python way to do things. One of the main objectives of the
abc
module was to introduce a mechanism to overloadisinstance()
, butisinstance()
checks are normally avoided in favour of duck typing. Use it if you need it, but not as a general pattern for defining interfaces.如有疑问,按照 Guido 的方式进行操作。
无下划线。只需将“抽象方法”定义为会引发 NotImplementedError 的单行代码:
When in doubt, do as Guido does.
No underscore. Just define the "abstract method" as a one-liner which raises NotImplementedError:
基本上,基类中的空方法在这里是不必要的。就这样做:
事实上,你通常甚至不需要Python中的基类。由于所有调用都是动态解析的,如果该方法存在,则会调用该方法,如果不存在,则会引发
AttributeError
。注意:重要的是在文档中提到
_concrete_method
需要在子类中实现。Basically, an empty method in the base class is not necessary here. Just do it like this:
In fact, you usually don't even need the base class in Python. Since all calls are resolved dynamically, if the method is present, it will be invoked, if not, an
AttributeError
will be raised.Attention: It is import to mention in the documentation that
_concrete_method
needs to be implemented in subclasses.