使用接口/抽象基类是Pythonic吗?
除了某种文档目的之外,我找不到它们的太多优点。如果我忘记实现在 ABC 中定义的方法,Python 会警告我,但由于我没有通过对象的接口引用我的对象,所以我可能会忘记在其接口中声明方法,而且我不会注意到它。 使用 ABC 来实现类似界面的行为是常见的做法吗?
I cannot find much advantage in them besides kind of documentation purpose. Python will warn me if I forget to implement a method I defined in a ABC but since I do not reference my objects by their interfaces I can forget to declare methods in their interfaces and I won't event notice it.
Is it common practice to use ABC's for interface-like behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就我个人而言,我发现抽象类在编写在一个开发人员和另一个开发人员之间进行交互的库或其他代码时最有用。
静态类型语言的优点之一是,当您使用错误的类型时,它会提前失败(通常早在编译时)。 ABC 允许 Python 通过动态类型获得同样的优势。
如果您的库代码鸭子类型缺少重要方法的对象,则在需要该方法之前它可能不会失败(这可能需要大量时间或将资源置于不一致的状态,具体取决于它的使用方式)。然而,对于 ABC,缺少的方法要么未使用正确的 ABC(并且未通过
instanceof
检查),要么已被 ABC“验证”。此外,ABC 是一种很好的方式来记录接口,无论是概念上还是通过文档字符串字面意思。
Personally, I find abstract classes to be most useful when writing libraries or other code which interfaces between one developer and another.
One of the advantages of statically-typed languages is that when you use the wrong type, it fails early (often, as early as compile time). ABCs allow Python to gain this same advantage with dynamic typing.
If your library code duck types an object which lacks a vital method, it likely won't fail until that method is needed (which could take significant time or put resources into an inconsistent state, depending on how it's used). With ABCs, however, a missing method either isn't using the correct ABC (and fails an
instanceof
check) or is "validated" by the ABC.Additionally, ABCs serve as an excellent way to document interfaces, both conceptually and, via docstrings, literally.
AFAIK,标准做法是使用
NotImplementedError
< /a> 未实现的抽象方法的异常。但我相信 ABC 可能被认为是 pythonic,因为它现在是 Python 标准库的一部分 。
AFAIK, the standard practice has been to use the
NotImplementedError
exception for unimplemented abstract methods.But I believe ABC might be considered pythonic, since it is now part of the Python standard library.