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.
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.
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