Exploring the Role of .__lt__() and .__gt__() in min() and max()
Exploring the Role of
max(). As you’ve learned so far, the built-in
max() functions are versatile enough to work with values of various data types, such as numbers and strings.
These methods are part of what Python calls rich comparison methods. Specifically,
.__gt__() support the less than (
<) and greater than (
>) operators, respectively. But what’s the meaning of support here?
When Python encounters a line such as seen on-screen, internally it does this. The takeaway is that you can use
max() with values of any data type that implement
As you can see, Python’s built-in data types implement the
.__gt__() special methods. So, you can feed any of these data types into
max(), with the only condition being that the involved data types are comparable.
Note that the implementation of both dunder methods requires an argument that’s typically named
other. This argument represents the second operand in the underlying comparison operations. For example, an expression such as
x < y,
x will be
y will be
other. Here, the dunder methods return the result of comparing two people’s
.birth_date attributes. You can see this working in practice on-screen.
If you have a class that defines
.__eq__() and other rich comparison methods, then this decorator will automatically supply the rest of the comparison methods. Note that if a given custom class doesn’t provide these methods, then its instances won’t support
Become a Member to join the conversation.