Sub topic 6
Making objects feel built-in with special methods
This chapter assumes you can define a class, write __init__, and use instance methods and attributes. Special methods let your own classes work with print, ==, +, and other built-in syntax.
What special methods are
A special method (also called a dunder method, for "double underscore") has a name like __repr__ or __add__. You rarely call these directly. Python calls them when you use certain syntax or built-in functions.
| You write | Python calls |
|---|---|
| `repr(x)` or showing `x` in the REPL | `x.__repr__()` |
| `x == y` | `x.__eq__(y)` |
| `x + y` | `x.__add__(y)` |
A readable representation with `__repr__`
Without __repr__, an object prints as something like <__main__.Vector object at 0x...>. That tells you nothing about its contents. Define __repr__ to return a string that shows the object's state. By convention, it looks like the code that would build the object.
The !r in an f-string applies repr() to the value. Strings then appear with quotes, which makes the output unambiguous.
Equality with `__eq__`
By default, == compares identity: two objects are equal only if they are the same object. For value-like classes, define __eq__ to compare contents.
Return NotImplemented (not False) when other is a type you don't handle. This is a special value, not an exception. It tells Python to try the other operand's method, and if that also fails, Python falls back to a sensible default.
Arithmetic with `__add__`
__add__ implements +. It should normally return a new object and leave both operands unchanged. The same NotImplemented rule applies, so Vector(1, 2) + 5 raises a clear TypeError instead of an obscure AttributeError.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vector({self.x!r}, {self.y!r})"
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
print(Vector(1, 2) + Vector(3, 4)) # Vector(4, 6)
print(Vector(1, 2) == Vector(1, 2)) # True
print(Vector(1, 2) == (1, 2)) # FalseThe last line shows the fallback. Both Vector.__eq__ and tuple.__eq__ return NotImplemented, so Python compares identity and gives False.
Common errors
- Forgetting
__repr__. Debugging output and test failures become hard to read. - Returning
Falseinstead ofNotImplementedfor unsupported types. This blocks the other operand from handling the comparison. - Mutating an operand in
__add__. Users expecta + bto leaveaandbalone. - Defining
__eq__and then using the object in a set or as a dict key. When a class defines__eq__but not__hash__, Python sets__hash__toNone, so instances become unhashable. This is intentional, because equal objects must have equal hashes. If you need hashing, define__hash__consistently with__eq__, and only for objects that are not changed after creation.
Other special methods worth knowing
You can apply the same idea to many built-in behaviors.
__str__gives a friendly string forprint()andstr(). If missing, Python uses__repr__.__len__supportslen(x).__lt__and related methods support ordering with<.__getitem__supportsx[i].__bool__controls truth testing.
Start with __repr__. Add the others only when the class needs them.
Exercise
What does Vector(1, 2) + 5 do with the class above, and why?
Show answer
It raises TypeError. Vector.__add__ sees that 5 is not a Vector and returns NotImplemented. Python then tries int.__radd__, which also returns NotImplemented, so Python raises TypeError for the unsupported operand types.
Exercise
Add a __hash__ method to Vector so that {Vector(1, 2), Vector(1, 2)} has one element. What must be true about the objects for this to be safe?
Show answer
Define def __hash__(self): return hash((self.x, self.y)). It matches __eq__ because equal vectors produce equal tuples and therefore equal hashes. It is only safe if x and y are not changed after the object is placed in a set or used as a dict key, since a changed value would change the hash.