在Python中,`lt` 和 `gt` 是两个富比较方法,分别代表小于(`less than`)和大于(`greater than`)。这些方法允许你自定义类的实例之间的比较行为。
`__lt__(self, other)`: 如果 `self` 小于 `other`,返回 `True`,否则返回 `False`。
`__gt__(self, other)`: 如果 `self` 大于 `other`,返回 `True`,否则返回 `False`。
当你使用 `lt` 和 `gt` 运算符比较两个对象时,Python 会自动调用这些方法。例如:
class Distance:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
d1 = Distance(10)
d2 = Distance(20)
print(d1 < d2) 输出 True,因为 10 小于 20
print(d1 > d2) 输出 False,因为 10 不大于 20
在上面的例子中,`Distance` 类定义了 `__lt__` 方法,使得我们可以使用 `lt` 运算符来比较 `Distance` 类的实例。