python中__lt__的作用

python中__lt__的作用

   小白     2021年2月27日 08:56     1715    

__lt__python中的魔法函数,通常称其为富比较方法,object.__lt__(self, other)

其作用是实现同类对象进行“比较”的方法

 

使用比较符号可以直接比较数字,字母等,但是如果要对比类的实例该如何对比呢?

示例1.

class People(object):
   
def __init__(self,name , age , weight):
       
self.name = name
       
self.age = age
       
self.weight = weight

zhang = People('zhang' , 23 , 64)
zhao = People(
'zhao' , 34 , 57)
li = People(
'li' , 27 , 76)

print(zhang > zhao)

这样直接进行比较,是没有办法比较的。

运行结果:

Traceback (most recent call last):

  File "D:/project/python-test/test_queue.py", line 22, in <module>

    print(zhang > zhao)

TypeError: '>' not supported between instances of 'People' and 'People'

 

示例2.

class People(object):
   
def __init__(self,name , age , weight):
       
self.name = name
       
self.age = age
       
self.weight = weight

   
def __lt__(self, other):
       
print("compare.....")
       
return self.age < other.age

zhang = People('zhang' , 23 , 64)
zhao = People(
'zhao' , 34 , 57)
li = People(
'li' , 27 , 76)
print(zhang > zhao)

运行结果:

compare.....

False

可以看到在执行print(zhang>zhao)的时候,其会自动调用__lt__这个魔法函数。其根据实例的age进行的对比。

当然也可以使用weight进行对比,只要在__lt__函数中使用

return self.weight<other.weight

进行值的返回。

 

示例3.

在类对象进行.sort()sorted()也是根据__lt__进行的排序。

class People(object):
   
def __init__(self,name , age , weight):
       
self.name = name
       
self.age = age
       
self.weight = weight

   
def __lt__(self, other):
       
print("compare.....")
       
return self.age<other.age

   
def __str__(self):
       
return 'name:'+ self.name+'\n' + 'age:'+ str(self.age)+'\n' + 'weight:' + str(self.weight) + '\n'

zhang = People('zhang' , 23 , 64)
zhao = People(
'zhao' , 34 , 57)
li = People(
'li' , 27 , 76)
cmp = [zhang
, zhao, li]
s_cmp =
sorted(cmp)
for i in s_cmp:
   
print(i)

根据下边的结果可以看到其依据age进行了排序。

运行结果:

compare.....

compare.....

compare.....

compare.....

name:zhang

age:23

weight:64

 

name:li

age:27

weight:76

 

name:zhao

age:34

weight:57


文章评论

0

其他文章