前言
Python 中的 NotImplemented 和 NotImplementedError 很像,都用来表示没有实现的意思。它们具体有什么区别呢?
NotImplemented
NotImplemented 是 Python 中的一个特殊常量,注意它不是一个异常类,是一个值。所以它是用在 return 后面,而不是 raise。它是 types.NotImplementedType 类型的唯一实例。
它主要用于重载自定义二元方法中,如 __add__, __eq__,__lt__ 等,这些方法用于定义类实例的相加(+)、相等(==)、小于(<)等比较操作。当方法返回 NotImplemented 时,表示这个操作是没有实现的。
class MyClass:
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, MyClass):
return MyClass(self.value + other.value)
elif isinstance(other, int):
return MyClass(self.value + other)
else:
return NotImplemented
def __str__


被折叠的 条评论
为什么被折叠?



