Skip to main content
 首页 » 编程设计

python之__gt__ 与 > 等等

2025年05月04日11birdshome

一些 python 类有一些运算符,例如 __gt__或 __lt__ , 它们是用 fortran 语言命名的。

上述运算符和<有什么区别?或 > ?
使用 __operators__ 不是更好吗?比<或 > ?

请您参考如下方法:

__gt__方法是 > 的实现,同样其他比较运算符也有类似的方法:

object.__lt__(self, other)

object.__le__(self, other)

object.__eq__(self, other)

object.__ne__(self, other)

object.__gt__(self, other)

object.__ge__(self, other)

These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: x<y calls x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y).

Source

通常使用运算符 >等在代码中。但是你需要使用 __gt__以及在自己的类上实现功能的类似方法。

你应该(几乎总是)不使用 __gt__方法,因为数据模型还定义了一些在这些方法之外处理的特殊情况。

例如,如果一个操作数没有实现比较,那么它会尝试使用交换的运算符进行反向比较:

>>> (1).__gt__(2.5) 
NotImplemented 
 
>>> (2.5).__lt__(1) 
False 
 
>>> 1 > 2.5 
False 

如果您需要“功能比较”,您应该使用 operator模块:

>>> from operator import gt 
>>> gt(1, 2.5) 
False