在python中,__lt__ 是用于实现“小于”比较的方法。它对应的是 < 运算符。如果你希望自定义对象支持 < 比较运算,可以通过实现 __lt__ 方法来实现。
不使用__lt__小于符号比较方法:
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
stu1 = Student("周杰伦",11)
stu2 = Student("周杰伦",13)
print(stu1 < stu2)
# 结果:Traceback (most recent call last):
# File "F:\demo2\test3.py", line 8, in <module>
# print(stu1 < stu2)
# ^^^^^^^^^^^
#TypeError: '<' not supported between instances of 'Student' and 'Student'
print(stu1.age < stu2.age)
# 结果:True
使用 __lt__小于符号比较方法:
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __lt__(self,other):
return self.age < other.age
stu1 = Student("周杰伦",11)
stu2 = Student("周杰伦",13)
print(stu1 < stu2) #结果:Ture
print(stu1 > stu2) #结果:Falue
在这个__lt__方法中我们可以看见other这个参数,这个指的是另一个类对象。
·方法名 : __lt__
·传入参数 :other——另一个对象
·返回值 :Ture或Flase