"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 !=)."
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
[...] 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.
这是因为
__lt__()
和相关的比较方法在列表排序等中非常常用。有时算法会选择另一种方法或选择默认的赢家。除非捕获到异常,否则引发异常将中断排序,而NotImplemented
不会引发异常,可以在进一步的测试中使用。http://jcalderone.livejournal.com/32837.html
总结这个链接:
一个原因是表现。在富比较这样的情况下,您可以在短时间内执行大量操作,设置和处理大量异常可能需要比简单地返回
NotImplemented
值长得多。因为它们有不同的用例。
引用文档(Python3.6):
NotImplemented
exception NotImplementedError
有关详细信息,请参见链接。
相关问题 更多 >
编程相关推荐