Friday, December 27, 2024
Google search engine
HomeLanguagesPython – __lt__ magic method

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.

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments