Python NotImplemented constant
从
1 2 3 4 5 6 | class A(object): def __lt__(self, a): return NotImplemented def __add__(self, a): return NotImplemented |
python文档说:
NotImplemented
Special value which can be returned by the"rich comparison"
special methods (__eq__() ,__lt__() ,
and friends), to indicate that the
comparison is not implemented with
respect to the other type.
号
它不讨论其他特殊的方法,也不描述行为。
它似乎是一个神奇的对象,如果从其他特殊方法返回,则会引发
例如
1 | print A() < A() |
号
打印
1 | print A() + 1 |
提出
从python语言参考:
For objects x and y, first
x.__op__(y)
is tried. If this is not implemented
or returns NotImplemented,
y.__rop__(x) is tried. If this is also
not implemented or returns
NotImplemented, a TypeError exception
is raised. But see the following
exception:Exception to the previous
item: if the left operand is an
instance of a built-in type or a
new-style class, and the right operand
is an instance of a proper subclass of
that type or class and overrides the
base's__rop__() method, the right
operand's__rop__() method is tried
before the left operand's__op__()
method. This is done so that a
subclass can completely override
binary operators. Otherwise, the left
operand's__op__() method would always
accept the right operand: when an
instance of a given class is expected,
an instance of a subclass of that
class is always acceptable.
号
实际上,从
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # 2.6 >>> class A(object): ... def __lt__(self, other): ... return NotImplemented >>> A() < A() True # 3.1 >>> class A(object): ... def __lt__(self, other): ... return NotImplemented >>> A() < A() Traceback (most recent call last): File"<stdin>", line 1, in <module> TypeError: unorderable types: A() < A() |
有关详细信息,请参阅订购比较(3.0文档)。
如果您从
如果从一个丰富的比较函数返回