Skip to content
IT Vizag
← Objects & Classes

▶ 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

Lesson 4 of 10 · 2 min read

__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

🔒 Code example: sign up free (above) to unlock it.
🔒 Code example: sign up free (above) to unlock it.

__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:

🔒 Code example: sign up free (above) to unlock it.

!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:

🔒 Code example: sign up free (above) to unlock it.

Define what equality means for your class:

🔒 Code example: sign up free (above) to unlock it.

More special methods

  • __len__: makes len(obj) work
  • __lt__: makes < work, so sorted() can sort your objects
  • __add__: makes + work
  • __contains__: makes in work
🔒 Code example: sign up free (above) to unlock it.
Tip: Don't go overboard. Add special methods when they make your object behave the way a reader would naturally expect; __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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend