Implement equality based on the meaningful values of your class.
What You Will Learn
Object identity tells you whether two references point to the same object; __eq__ lets a class define when two separate instances should count as equal. Return NotImplemented for unrelated types so Python can try reflected comparison correctly. Consider hash behavior if equal objects will be used as dictionary keys.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
class Ticket:
def __init__(self, code):
self.code = code
def __eq__(self, other):
if not isinstance(other, Ticket):
return NotImplemented
return self.code == other.code
first = Ticket("A-1")
second = Ticket("A-1")
print(first == second)
print(first is second)
How the Example Works
- The class Ticket groups data and behavior; its methods run when called on an instance.
- The variable first holds the result of Ticket('A-1'). Later lines use that value or inspect how it changes.
- The variable second holds the result of Ticket('A-1'). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
True
False
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Add another field and decide whether that field should affect equality.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Returning False for every unsupported type without giving reflected equality a chance.
- Defining value equality and then assuming instances remain hashable without reviewing __hash__.
Key Takeaways
- Implement equality based on the meaningful values of your class.
- Object identity tells you whether two references point to the same object; __eq__ lets a class define when two separate instances should count as equal.
- Apply this operation only after checking the assumptions and input conditions shown in the example.