Python 中的魔术方法(三)自定义比较方法, __eq__(==), __lt__(<)等方法

相较于 a.is_equal(b), a.is_greater_than(b) 这种语法的函数调用来进行对象的对比, 使用运算符的比较  a == b,  a >  b 这样的语法更加直观。 

Python 种提供了一系列的魔术方法, 来实现对象的对比。

方法 说明 运算符
__eq__(self, other) 定义相等运算符的行为 ==
__ne__(self, other) 定义不等式运算符的行为 !=
__lt__(self, other)  定义小于运算符的行为 <
__le__(self, other) 定义小于或等于运算符的行为 <=
__gt__(self, other)
普通文本型问题。 在 Python 中,`__lt__` 是一个**魔术方法(Magic Method)**,用于定义对象之间的**小于**比较行为(即 `&lt;` 运算符的行为)。当你使用 `&lt;` 来比较两个对象时,Python 会自动调用该对象的 `__lt__` 方法。 --- ### 基本语法: ```python class 类名: def __lt__(self, other): # 比较逻辑 return 布尔值或 NotImplemented ``` - `self` 是当前对象。 - `other` 是要比较的对象。 - 返回 `True` 或 `False`,或者返回 `NotImplemented` 表示不支持该比较。 --- ### 示例: ```python class Student: def __init__(self, name, score): self.name = name self.score = score def __lt__(self, other): if not isinstance(other, Student): return NotImplemented return self.score &lt; other.score s1 = Student("Alice", 85) s2 = Student("Bob", 90) print(s1 &lt; s2) # 输出:True,因为 85 &lt; 90 print(s2 &lt; s1) # 输出:False ``` --- ### 与其他比较方法的关系: - `__lt__` 是实现对象比较逻辑中最常用的方法之一。 - 配合 `__eq__` 使用后,可以与 `functools.total_ordering` 装饰器结合,自动生成 `&lt;=`, `>`, `>=` 等比较操作。 --- ### 结合 `functools.total_ordering` 示例: ```python from functools import total_ordering @total_ordering class Product: def __init__(self, name, price): self.name = name self.price = price def __eq__(self, other): return self.price == other.price def __lt__(self, other): return self.price &lt; other.price ``` 现在 `Product` 类支持所有比较操作符: ```python p1 = Product("A", 100) p2 = Product("B", 150) print(p1 &lt; p2) # True print(p1 > p2) # False print(p1 == p2) # False print(p1 &lt;= p2) # True print(p1 >= p2) # False ``` --- ### 总结: `__lt__` 是用于定义 `&lt;` 运算符行为的魔术方法,常用于自定义类的排序或比较逻辑。配合 `__eq__` 和 `total_ordering` 可大幅减少手动实现比较方法的工作量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值