gpt4 book ai didi

Python NotImplemented 常量

转载 作者:IT老高 更新时间:2023-10-28 22:12:12 27 4
gpt4 key购买 nike

查看decimal.py,它在很多特殊的方法中使用了NotImplemented。例如

class A(object):
def __lt__(self, a):
return NotImplemented

def __add__(self, a):
return NotImplemented

Python docs say :

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.

它没有谈论其他特殊方法,也没有描述行为。

它似乎是一个神奇的对象,如果从其他特殊方法返回会引发 TypeError,而在“丰富的比较”中,特殊方法什么也不做。

例如

print A() < A()

打印True,但是

print A() + 1

引发 TypeError,所以我很好奇发生了什么以及 NotImplemented 的用法/行为是什么。

最佳答案

NotImplemented 允许您指示两个给定操作数之间的比较尚未实现(而不是指示比较有效,但产生 False,因为两个操作数)。

来自 Python Language Reference :

For objects x and y, first x.__op__(y)is tried. If this is not implementedor returns NotImplemented,y.__rop__(x) is tried. If this is alsonot implemented or returnsNotImplemented, a TypeError exceptionis raised. But see the followingexception:

Exception to the previousitem: if the left operand is aninstance of a built-in type or anew-style class, and the right operandis an instance of a proper subclass ofthat type or class and overrides thebase's __rop__() method, the rightoperand's __rop__() method is triedbefore the left operand's __op__()method. This is done so that asubclass can completely overridebinary operators. Otherwise, the leftoperand's __op__() method would alwaysaccept the right operand: when aninstance of a given class is expected,an instance of a subclass of thatclass is always acceptable.

关于Python NotImplemented 常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1062096/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com