Dunder Methods
Your account works. Now try to look at one.
<__main__.Account object at 0x7f...>. That is the least useful sentence in
programming, and it's what every log line, every debugger and every error message
will show you until you fix it.
Dunder methods — double-underscore names like __repr__ — are how a type
plugs into Python itself. They're the difference between a class you built and a
type that feels native.
__repr__: be readable
The convention: make it look like the code that would recreate the object. When something goes wrong at 3am, that string is what you'll be reading.
Note the second line — putting objects in a list shows their __repr__, not
__str__. That's why __repr__ is the one to write first.
It must return a string, not print one:
TypeErrorRun it and read the error. Then make it print Account(Ada) exactly once.
__eq__: say what equal means
By default, two objects are equal only when they're the same object:
class Money:
def __init__(self, amount):
self.amount = amount
print(Money(5) == Money(5))Define what equality means for your type and it behaves the way people expect:
__len__ and __add__: hook the built-ins
len(x) isn't a method call — it's Python asking x for its __len__. The same
goes for + and __add__.
Notice __add__ returns a new Playlist rather than modifying self. That
matches how + behaves for numbers and strings — a + b should never change a
— and breaking that expectation is worse than not implementing + at all.
Step through the addition and watch a third object appear:
a and b are untouched. c is new.
Which ones are worth it
You will not implement most of them. In practice:
__repr__— always. It costs one line and pays back every time you debug.__eq__— when your type is a value (money, a point, a date) rather than an identity (a user session, a connection).__len__,__iter__,__getitem__— when your type genuinely wraps a collection, solen(),forand[0]mean the obvious thing.__add__and friends — rarely, and only when the operator has one obvious meaning. Clever operators are how libraries become unreadable.
🎯 Your turn
Give Account a __repr__ returning "Account(owner='Ada', balance=100)" and an
__eq__ treating two accounts as equal when owner and balance match. Then
write describe(owner, balance) returning the repr string:
describe("Ada", 100)→"Account(owner='Ada', balance=100)"describe("Sam", 0)→"Account(owner='Sam', balance=0)"
Hint — watch the quotes: the owner is quoted inside the string, the balance isn't. An f-string handles both.
Then press ▶ Run and hit ✓ Check. This one closes the section. ✅
