▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Special methods
__str__, __repr__ and __eq__ make objects print and compare nicely.
🎬 Video version coming soon — read it now
Python has special methods (also called "dunder" methods, for double underscore) that let your objects work with built-in features like print, ==, len and +.
__str__: how print shows your object
__repr__: for developers
__repr__ is the "official" text, shown in the Colab output, in lists and in the debugger. Make it look like the code that would create the object:
!r puts quotes around the string. If you write only one of the two, write __repr__; Python uses it for print too.
__eq__: what "equal" means
By default, two objects are equal only if they're the same object:
Define what equality means for your class:
More special methods
__len__: makeslen(obj)work__lt__: makes<work, sosorted()can sort your objects__add__: makes+work__contains__: makesinwork
__repr__ is worth adding to almost every class.In one line
Special methods like __str__, __repr__, __eq__ and __len__ let your objects work naturally with print, ==, len and more.
Share with a friend