The __gt__()
method is part of the comparison magic methods in Python. It is used to implement the internal workings of the greater than (>
) operator on objects of a given class. This means that when we call the >
operator on objects i.e x > Y
, Python literally calls the __gt__()
method on the object x, with the argument y i.e x.__gt__(y)
.
Most builtin data types have this method defined by default , this makes it possible to use the >
operator to tell whether one value is greater than the other.
One common application of the the __gt__()
method( and consequently the >
operator) is in sorting. This is because the method evaluates logically whether one value is greater than the other thus establishing order in the items.
Defining the __gt__() method for custom objects
In order for a user-defined objects to be able to use the greater than operator( >
), it must define the __gt__()
method.
class MyClass:
def __gt__(self, other):
#statements
self |
This is a compulsory parameter for all instance methods. It references the current instance of the class. |
other |
The other object to be compared with the current instance(self ) |
The method should define only two required method, i.e self
and other
. It should return a boolean value indicating whether self
is greater than other
. True if so and False
otherwise.
In some cases, it is essential to check explicitly whether the "other" object is actually an instance of the current class. This ensures that we avoid incorrect and unintentional result in the case where the two classes shares attributes with same names. This can be achieved using the builtin isinstance()
method as in above example.
Another Example: