本文介绍了为什么返回 NotImplemented 而不是引发 NotImplementedError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 有一个名为 NotImplemented.

Python has a singleton called NotImplemented.

为什么有人想要返回 NotImplemented 而不是提高 NotImplementedError 异常?会不会让查找错误变得更加困难,例如执行无效方法的代码?

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.

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

总结该链接:

"NotImplemented 向运行时发出信号,它应该要求其他人满足该操作.在表达式 a == b 中,如果 a.__eq__(b) 返回 NotImplemented,然后 Python 尝试 b.__eq__(a).如果 b 知道足够返回 TrueFalse,则表达式可以成功.如果不成功,则运行时将回退到内置行为(基于 ==!=)."

这篇关于为什么返回 NotImplemented 而不是引发 NotImplementedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 12:49