The __le__()
method implements the internal workings of the less than or equal to operator ( <=
) . When we use the <=
operator as in x <= y
, Python internally calls the __le__()
method on object x
with y
as the argument, i.e x.__le__(y)
.
Most builtin data types have this method implemented. This makes it possible to use the <=
operator on various data type objects.
print(int(10).__le__(20)) # same as print(10 <= 20)
print("abc".__le__("xyz"))#Same as print("abs" <= "xyz")
print([5, 4, 3].__le__([1, 2, 3]))#Same as print([5, 4, 3] <= [1, 2, 3])
In most cases, the method is used primarily with objects belonging to the same class/type. Either the TypeError
or the NotImplemented
exception may be raised if we use the method with objects from different classes.
print(int(10).__le__("10"))
Implementing the __le__() method for custom objects
In order to be able to use the <=
operator on user-defined objects, the involved objects must implement the __le__()
method based on their internal logic.
class MyClass:
def __le__(self, other):
#Statements
#A class for heights in meters
class Height:
def __init__(self, value):
self.value = value
#define the __le__() method
def __le__(self, other):
if isinstance(other, Height):
#Check that the 'other' object is an instance of this class
return self.value <= other.value
#Raise an error if 'other' is not an instance of this class
raise TypeError("Both objects should be instances of 'Height'")
h1 = Height(5.4)
h2 = Height(7.5)
h3 = Height(3.0)
print(h1 <= h2)
print(h2 <= h3)