Equality and Representation
Explore how to make custom Python classes behave like built-in types by defining __str__ for readable output, __repr__ for unambiguous representation, and __eq__ to compare objects based on their data rather than identity. This lesson helps you create intuitive and debug-friendly class designs.
The classes we have created so far are useful for storing data, but they still feel unfamiliar compared to Python’s built-in types. If we print a custom object, Python will show a cryptic memory address. Similarly, when we compare two objects that contain identical data using ==, Python will report that they are different.
To make our objects behave more intuitively (like numbers or strings), we need to teach them how to describe themselves and how to define equality. In this lesson, we will override specific dunder (double underscore) methods, allowing our classes to control how they are displayed and how comparisons are performed.
The default behavior
By default, Python does not know how to display the contents of custom objects or compare them based on their data. In these situations, Python falls back to default behavior. It prints the object's memory address and evaluates equality using identity. This means it checks whether two variables reference the same object in memory.
Let’s look at a simple Spaceship class without any special methods:
Lines 1–4: ...