Python program to overload equality -Operator Overloading
Operator overloading allows the same operator to have different meanings based on the operands used. In Python, special methods (also known as dunder methods) help in customizing the behavior of built-in operators. In this article, we will explore how to overload the equality operator (==) and the less than operator (<) in Python.
Below is a Python program demonstrating operator overloading for the equality (==) and less than (<) operators using the __eq__
and __lt__
methods.
# Python program to overload equality (==) and less than (<) operator
class A:
def __init__(self, a):
self.a = a
# Overloading the less than (<) operator
def __lt__(self, other):
if self.a < other.a:
return "ob1 is less than ob2"
else:
return "ob2 is less than ob1"
# Overloading the equality (==) operator
def __eq__(self, other):
if self.a == other.a:
return "Both are equal"
else:
return "Not equal"
# Creating instances of class A
ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2) # Output: ob1 is less than ob2
ob3 = A(4)
ob4 = A(4)
print(ob3 == ob4) # Output: Both are equal
__lt__
(less than operator <)
self.a
is smaller than other.a
.self.a
is smaller, it returns "ob1 is less than ob2".
__eq__
(equality operator ==)
self.a
is equal to other.a
.Operator overloading is a powerful feature in Python that enhances object-oriented programming by enabling intuitive comparisons between custom objects. By overloading the equality (==) and less than (<) operators, we can define how our objects should be compared. This improves code clarity and provides a more natural way to implement object interactions.