为什么返回NotImplemented而不是提升NotImplementedError [英] Why return NotImplemented instead of raising NotImplementedError

查看:455
本文介绍了为什么返回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 知道足够返回 True False ,然后表达式可以成功,如果没有,则运行时将回到内置行为(基于 == != )。

"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而不是提升NotImplementedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆