Python __ge__() 语法
__ge__() 是 Python 的一个特殊方法(又称 “魔法方法” 或 “双下划线方法”),它用于定义当两个对象进行 “大于等于(>=)” 比较时,如何判断它们的大小。
当我们使用 “>=” 运算符比较两个对象时,Python 内部会自动调用它们的 __ge__() 方法。
语法:
class MyObject:
def __ge__(self, other):
# 返回 True, False 或 NotImplemented
return self.value >= other.value
说明:
__ge__() 方法接收以下 2 个参数。
self(必选):表示调用 “>=” 运算符的左侧对象。other(必选):表示调用 “>=” 运算符的右侧对象。
__ge__() 方法必须返回一个布尔值(True 或 False),以表示比较的结果。如果不支持比较(比如类型不兼容),则应返回 NotImplemented。如果返回 NotImplemented,Python 可能会尝试调用 other 对象的 __lt__() 方法来尝试反向比较。
为了确保比较操作的一致性,我们通常建议在实现 __ge__() 时,也实现其他比较方法,如 __lt__()、__le__()、__eq__()、__ne__() 和 __gt__() 等。
提示:我们可以借助 functools.total_ordering 装饰器来自动实现其他比较方法,它只需要你实现 __eq__() 和任意一个方法,就可以自动生成所有其他比较方法。
Python __ge__() 摘要
| 属于 | Python 魔法方法 |
|---|---|
| 使用频率 | 中 |
| 官方文档 | 查看 |
| 相关方法 | __lt__()、__le__()、__eq__()、__ne__()、__gt__() |
Python __ge__() 示例
接下来,我们通过几个简单的例子来讲解一下 Python __ge__() 方法是如何使用的。
示例 1:__ge__() 基本用法
class CustomNumber:
def __init__(self, value):
self.value = value
def __ge__(self, other):
if isinstance(other, CustomNumber):
return self.value >= other.value
elif isinstance(other, (int, float)):
return self.value >= other
return NotImplemented
# 创建 CustomNumber 类的实例
num1 = CustomNumber(100)
num2 = CustomNumber(90)
num3 = CustomNumber(100)
# 使用 >= 运算符进行比较
print(num1 >= num2) # True
print(num2 >= num1) # False
print(num1 >= num3) # True
运行结果如下。
True
False
True
分析:
在这个例子中,我们定义了一个 CustomNumber 类,并为其实现了 __ge__() 方法。当比较两个 CustomNumber 对象时,该方法其实比较的是它们内部的 value 属性。
示例 2:__ge__() 比较不同类型对象
class Weight:
def __init__(self, kilograms):
self.kilograms = kilograms
def __ge__(self, other):
if isinstance(other, Weight):
return self.kilograms >= other.kilograms
elif isinstance(other, (int, float)):
# 允许与数字(表示公斤)直接比较
return self.kilograms >= other
return NotImplemented # 如果类型不兼容,返回 NotImplemented
# 创建 Weight 类的实例
w1 = Weight(50)
w2 = Weight(49.9)
# 与 Weight 对象比较
print(w1 >= w2) # True
# 与整数比较
print(w1 >= 50) # True
print(w1 >= 51) # False
# 与浮点数比较
print(w1 >= 49.99) # True
运行结果如下。
True
True
False
True
分析:
在 Weight 类中,我们手动实现了 __ge__() 方法。该方法支持两个 Weight 对象进行比较,也支持 Weight 对象与 int、float 值进行比较。
例如,w1 >= 50 比较的是 w1.kilograms (50) 是否大于等于 50,因此返回结果为 True。
示例 3:__ge__() 结合 functools.total_ordering
import functools
@functools.total_ordering
class Phone:
def __init__(self, brand, price):
self.brand = brand
self.price = price
def __eq__(self, other):
if not isinstance(other, Phone):
return NotImplemented
return self.price == other.price
def __ge__(self, other):
if not isinstance(other, Phone):
return NotImplemented
return self.price >= other.price
def __repr__(self):
return f'Phone({self.brand}, {self.price}元)'
# 创建实例
phone1 = Phone('小米手机', 3000)
phone2 = Phone('一加手机', 2000)
phone3 = Phone('华为手机', 3000)
# 使用 >= 运算符
print(phone1 >= phone2) # True
print(phone2 >= phone1) # False
print(phone1 >= phone3) # True
# 由于 @total_ordering,其他比较运算符也可用
print(phone1 < phone2) # False
print(phone1 == phone3) # True
print(phone2 <= phone1) # True
运行结果如下。
True
False
True
False
True
True
分析:
通过使用 @functools.total_ordering 装饰器,我们只需要实现了 __eq__() 和 __ge__()。然后其他的比较运算符(如 <、==、<=)的行为都由 total_ordering 自动推导出来。这使得 Phone 类的比较逻辑更加完整和一致,同时减少了需要编写的代码量。
例如,phone1 < phone2 会根据 phone1 >= phone2 的结果进行推导,最终返回结果为 False。
