NotImplemented
作用
对象间的比较时(调用对象的 __eq__
, __lt__
),如果对应的方法返回了 NotImplemented
,则会从右操作数的角度调用方法进行比较。
In [22]: class A(object):
...: def __init__(self, num):
...: self.num = num
...: def __eq__(self, other):
...: print('call A __eq__')
...: return NotImplemented
...:
...:
In [23]: class B(object):
...: def __init__(self, num):
...: self.num = num
...: def __eq__(self, other):
...: print('call B __eq__')
...: return self.num == other.num
...:
In [24]: a = A(2)
In [25]: b = B(2)
In [26]: a == b
call A __eq__
call B __eq__
Out[26]: True
In [27]: b == a
call B __eq__
Out[31]: True
可以看到首先调用了 a.__eq__(b)
,由于返回了 NotImplemented
常量,所以 b.__eq__(a)
被调用。
与 NotImplementedError 的区别
- 抛出异常时,根据初始化init方法,携带字符串,方便阅读,这也是写日志的最好方法
- 若不按照初始化方法进行抛出异常时,通常采用直接携带字符串并打印出相关字符串
- NotImplemented在源码中就不是一个类,而是NotImplementedType的一个实例
- NotIplementedError在源码 中本身就是一个类,而且继承RuntimeError,因此这个才是正则体系中的错误类
print(type(NotImplemented))
print(type(NotImplementedError))
import sys
try:
# raise FileNotFoundError
raise NotImplementedError('not implemented')
except Exception as f:
print(f.args)
print(f)
# 运行结果:
<class 'NotImplementedType'> #说明NotImplemented就是NotImplementedType的一个实例
<class 'type'> #说明NotImplementedError就是一个类
('not implemented',)
not implemented