为什么返回NotImplemented而不是引发NotImplementedE

2024-04-25 06:27:22 发布

您现在位置:Python中文网/ 问答频道 /正文

Python有一个名为^{}的单例。

为什么有人希望返回NotImplemented,而不是引发^{}异常?难道这不会让查找错误变得更困难,比如执行无效方法的代码吗?


Tags: 方法代码错误单例notimplemented
3条回答

这是因为__lt__()和相关的比较方法在列表排序等中非常常用。有时算法会选择另一种方法或选择默认的赢家。除非捕获到异常,否则引发异常将中断排序,而NotImplemented不会引发异常,可以在进一步的测试中使用。

http://jcalderone.livejournal.com/32837.html

总结这个链接:

"NotImplemented signals to the runtime that it should ask someone else to satisfy the operation. In the expression a == b, if a.__eq__(b) returns NotImplemented, then Python tries b.__eq__(a). If b knows enough to return True or False, then the expression can succeed. If it doesn't, then the runtime will fall back to the built-in behavior (which is based on identity for == and !=)."

一个原因是表现。在富比较这样的情况下,您可以在短时间内执行大量操作,设置和处理大量异常可能需要比简单地返回NotImplemented值长得多。

因为它们有不同的用例。

引用文档(Python3.6):

NotImplemented

should be returned by the binary special methods (e.g. __eq__(), __lt__(), __add__(), __rsub__(), etc.) to indicate that the operation is not implemented with respect to the other type

exception NotImplementedError

[...] In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.

有关详细信息,请参见链接。

相关问题 更多 >