码迷,mamicode.com
首页 > 编程语言 > 详细

[Python] NotImplemented 和 NotImplementedError 区别

时间:2014-08-09 22:56:49      阅读:1077      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   os   io   div   

  NotImplemented 是一个非异常对象,NotImplementedError 是一个异常对象。

>>> NotImplemented
NotImplemented
>>> NotImplementedError
<type exceptions.NotImplementedError>


>>> type(NotImplemented)
<type NotImplementedType>
>>> type(NotImplementedError)
<type type>

 

  如果抛出 NotImplemented 会得到 TypeError,因为它不是一个异常。而抛出 NotImplementedError 会正常捕获该异常。

>>> raise NotImplemented

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    raise NotImplemented
TypeError: exceptions must be old-style classes or derived from BaseException, not NotImplementedType


>>> raise NotImplementedError

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    raise NotImplementedError
NotImplementedError

 

为什么要存在一个 NotImplemented 和一个 NotImplementedError 呢?

  

  在 Python 中对列表进行排序时,会经常间接使用像 __lt__() 这类比较运算的方法。

  有时 Python 的内部算法会选择别的方法来确定比较结果,或者直接选择一个默认的结果。如果抛出一个异常,则会打破排序运算,因此如果使用 NotImplemented 则不会抛出异常,这样 Python 可以尝试别的方法。

  NotImplemented 对象向运行时环境发出一个信号,告诉运行环境如果当前操作失败,它应该再检查一下其他可行方法。例如在 a == b 表达式,如果 a.__eq__(b) 返回 NotImplemented,那么 Python 会尝试 b.__eq__(a)。如果调用 b 的 __eq__() 方法可以返回 True 或者 False,那么该表达式就成功了。如果 b.__eq__(a) 也不能得出结果,那么 Python 会继续尝试其他方法,例如使用 != 来比较。  

 

参考一

[Python] NotImplemented 和 NotImplementedError 区别,布布扣,bubuko.com

[Python] NotImplemented 和 NotImplementedError 区别

标签:style   blog   http   color   使用   os   io   div   

原文地址:http://www.cnblogs.com/ifantastic/p/3682268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!