Python – __lt__ magic method
Python __lt__ magic method is one magic method that is used to define or implement the functionality of the less than operator “<” , it returns a boolean value according to the condition i.e. it returns true if a<b where a and b are the objects of the class.
Python __lt__ magic method Syntax
Syntax: __lt__(self, obj)
- self: Reference of the object.
- obj: It is a object that will be compared further with the other object.
Returns: Returns True or False depending on the comparison.
YES <class 'str'>
Python __lt__ magic method Example
Traceback (most recent call last):
File “/home/5e1498c49d4f318ce8c96b9b70d245f6.py”, line 7, in <module>
print(student1_marks < student2_marks)
TypeError: ‘<‘ not supported between instances of ‘GFG’ and ‘GFG’
We can see that type error is generated as soon as we try to run this code because for this code we haven’t defined any __lt__ method so we can’t use the ‘<‘ operator for the same.
Hence we’ll have to define the __lt__ method first.
Here we have seen how we can define our own less than dunder method and return customized value from it. Also, we have seen what type of problem we face if we don’t define a __lt__ method.