A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-__lt__-magic-method/ below:

Python - __lt__ magic method

Python - __lt__ magic method

Last Updated : 04 Sep, 2022

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)

Returns: Returns True or False depending on the comparison.

Note: We can return any type of value from the __lt__ method and later we can convert it into a boolean value by the built-in method bool(), i.e.

Python3
class GFG:
    def __lt__(self, other):
        return "YES"
obj1 = GFG()
obj2 = GFG()

print(obj1 < obj2) 
print(type(obj1 < obj2))

Output:

YES
<class 'str'>
Python __lt__ magic method Example Python3
class GFG:
    def __init__(self, Marks):
        self.Marks = Marks
student1_marks = GFG(90)
student2_marks = GFG(88)

print(student1_marks < student2_marks)

Output:

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'

Explanation:

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.

Python3
class GFG:
    def __init__(self, Marks):
        self.Marks = Marks
    def __lt__(self, marks):
          return self.Marks < marks.Marks

student1_marks = GFG(90)
student2_marks = GFG(88)

print(student1_marks < student2_marks)
print(student2_marks < student1_marks)

Output:

False
True
Conclusion:

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4