The lt() Method
The __lt__() method ("less than") controls what the < operator does for your own objects.
Example
Compare two Person objects by age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __lt__(self, other):
return self.age < other.age
p1 = Person("Emil", 22)
p2 = Person("Tobias", 19)
print(p1 < p2)
Compare Without lt()
Without __lt__(), comparing two objects with < raises an error:
Example
Remove __lt__(), and the comparison fails:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Emil", 22)
p2 = Person("Tobias", 19)
print(p1 < p2)
Sorting with lt()
Python also uses __lt__() to sort objects, with functions like sorted().
The sorted() function returns a list with the given objects, sorted as specified in the __lt__() method.
Example
Sort a list of Person objects by age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __lt__(self, other):
return self.age < other.age
p1 = Person("Emil", 22)
p2 = Person("Tobias", 19)
p3 = Person("Linus", 15)
x = sorted([p1, p2, p3])
print(x[0].age)
Note:
sorted()returns a new list, ordered by age.x[0]is thePersonwith the lowest age. You can sort as many objects as you like - not just two or three.
Sorting Without lt
The sorted() function relies on <, so without __lt__(), it fails with the same kind of error:
Example
Remove __lt__(), and sorting fails:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Emil", 22)
p2 = Person("Tobias", 19)
p3 = Person("Linus", 15)
x = sorted([p1, p2, p3])