问题描述
Python有一个单例,名为。
Python has a singleton called NotImplemented
.
为什么有人想要返回 NotImplemented
而不是提高异常?不会只是更难找到错误,比如执行无效方法的代码?
Why would someone want to ever return NotImplemented
instead of raising the NotImplementedError
exception? Won't it just make it harder to find bugs, such as code that executes invalid methods?
推荐答案
这是因为 __ lt __()
和相关的比较方法通常在列表类型等间接使用。有时,算法会选择尝试另一种方式或选择默认的赢家。除非被捕获,否则提出异常会被排除在外,而 NotImplemented
不会被提出,并可用于进一步的测试。
It's because __lt__()
and related comparison methods are quite commonly used indirectly in list sorts and such. Sometimes the algorithm will choose to try another way or pick a default winner. Raising an exception would break out of the sort unless caught, whereas NotImplemented
doesn't get raised and can be used in further tests.
总结链接:
这篇关于为什么返回NotImplemented而不是提升NotImplementedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!