The __ge__()
method implements the internal workings of the greater than or equal to operator ( >=
) for objects of a given class. This means that when we use the >=
operator as x >= y
, Python internally calls the __ge__()
method on x
and passes y
as the argument, i.e x.__ge__(y)
. The method returns a boolean value of True
if the current instance is greater than or equal to the other object, and False
otherwise.
Most builtin types have this method defined, making it possible to use the >=
operator on various builtin data type objects.
print(int(10).__ge__(5 *2)) # Same as print(10 >= 5*2)
print([1, 2].__ge__([3, 4])) #Same as print([1, 2] >= [3, 4])
print((3, 4).__ge__((2, 5))) #same as print((3, 4) >= (2, 5))
You should note that the method is usually defined to work with objects of the same class. Trying to use it with objects from different classes/types may result in a TypeError
being raised.
print(int(10) >= [1, 2])
The >=
operator (and indirectly the __ge__()
method) is commonly used in loops, such as for
and while
loops, to test whether or not the current value of a loop variable is greater than or equal to a specific value.
Implementing the __ge__() method for custom objects
In order for custom objects to be able to use the >=
operator, the involved objects must define the __ge__()
method.
class MyClass:
def __ge__(self, other):
#Statements
self |
This is a compulsory parameter for all instance methods. it references the current instance. |
other |
A required parameter representing the other objects in the comparison |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
#Define the __ge__() method
def __ge__(self, other):
if isinstance(other, Point):
#validate that the "other object belongs to this class"
return (self.x, self.y) >= (other.x, other.y)
#Raise an exception if the "other" object does not belong to this class
raise TypeError("Both objects should be instances of Point.")
p1 = Point(5, 6)
p2 = Point(4, 7)
p3 = Point(4, 7)
print(p1 >= p2)
print(p2 >= p3)
print(p2 >= p1)