为什么 numbers.Real 没有 __gt__ 作为抽象(或默认)方法?
Why does numbers.Real not have __gt__ as an abstract (or default) method?
查看 numbers.py 的源代码,没有 @abstractmethod
或 __gt__
或 __ge__
的实现。为什么是这样?这是一个错误吗?
文档明确指出:
To Complex, Real adds the operations that work on real numbers. In short, those are: a conversion to float, trunc(), divmod, %, <, <=, >, and >=. Real also provides defaults for the derived operations.
据我所知,>
和 >=
并非如此。
默认实现应该足够简单,因为 ABC Real
需要 __lt__
和 __le__
的实现。例如
def __gt__(self, other):
return operator.lt(other, self)
同样,为什么这不是 numbers.py
中的默认值?
您的默认设置有问题,默认设置不是一个好主意。如果 a.__gt__
不存在或 returns NotImplemented
,a > b
已经尝试 b.__lt__(a)
。如果 other
不知道如何将自己与 self
进行比较,则您的默认设置会导致 <
和 __gt__
反复相互回退的无限递归。
因为比较运算符回退到反向比较方法,实现 __lt__
和 __le__
足以使 >
和 >=
工作,至少在对象之间同类型的。但是,它不足以处理 1.0 < MyFloat(1.0)
。
查看 numbers.py 的源代码,没有 @abstractmethod
或 __gt__
或 __ge__
的实现。为什么是这样?这是一个错误吗?
文档明确指出:
To Complex, Real adds the operations that work on real numbers. In short, those are: a conversion to float, trunc(), divmod, %, <, <=, >, and >=. Real also provides defaults for the derived operations.
据我所知,>
和 >=
并非如此。
默认实现应该足够简单,因为 ABC Real
需要 __lt__
和 __le__
的实现。例如
def __gt__(self, other):
return operator.lt(other, self)
同样,为什么这不是 numbers.py
中的默认值?
您的默认设置有问题,默认设置不是一个好主意。如果 a.__gt__
不存在或 returns NotImplemented
,a > b
已经尝试 b.__lt__(a)
。如果 other
不知道如何将自己与 self
进行比较,则您的默认设置会导致 <
和 __gt__
反复相互回退的无限递归。
因为比较运算符回退到反向比较方法,实现 __lt__
和 __le__
足以使 >
和 >=
工作,至少在对象之间同类型的。但是,它不足以处理 1.0 < MyFloat(1.0)
。