How do I implement equality and ordering on a class?

In Python, you can implement equality and ordering in a class by defining the special methods `__eq__` and `__lt__` (less than). By doing so, you can use the equality operator (`==`) and ordering operators (`<`, `>`, etc.) with instances of your class.

Here’s an example of how to implement these features in a class called `Person`:

class Person: def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): return self.age == other.age def __lt__(self, other): return self.age < other.age # Example usage person1 = Person("Alice", 30) person2 = Person("Bob", 25) # Check equality print(person1 == person2) # Output: False # Check ordering print(person1 < person2) # Output: False print(person1 > person2) # Output: True

Python equality ordering class methods __eq__ __lt__ object comparison