Skip to the solution
MediumDSA8 min read

What are dunder (magic) methods?

1.1k views

The problem

Question presented to candidate: "You keep seeing methods like __init__, __len__ and __add__ with double underscores on both sides. What are these dunder or magic methods, who calls them, and how would you use them to make your own class work with operators and built-ins?"

What a strong answer should cover:

  • Dunder ("double underscore") methods are special method names that Python's syntax and built-ins call for you: a + b calls type(a).__add__(a, b), len(x) calls __len__, print(x) calls __str__, with calls __enter__/__exit__.
  • They let a user-defined class implement protocols (number, sequence, container, iteration, context manager, callable) so it behaves like a built-in type.
  • Binary operators return the NotImplemented singleton when they cannot handle the other operand, so Python tries the reflected method (__radd__) and finally raises TypeError.
  • Implicit invocation looks the method up on the type, not on the instance: setting obj.__len__ on an instance does not change len(obj).
  • Defining __eq__ without __hash__ sets __hash__ to None, which makes instances unhashable.
  • You implement dunders, you rarely call them directly: use len(x) not x.__len__(); and you do not invent new __names__ of your own.

Code / implementation expected: Yes โ€” a small class (a vector, money or a deck) with __repr__, __eq__, an arithmetic operator returning NotImplemented, and a container method such as __len__.

  • oop
  • dunder

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read ยท 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonOperator overloading with a Vector: __add__, __rmul__, __eq__, NotImplemented
PythonProtocols: sequence via __getitem__, __call__, with, and type-level lookup

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 40 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What do the global and nonlocal keywords do?

Continue