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 + bcallstype(a).__add__(a, b),len(x)calls__len__,print(x)calls__str__,withcalls__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
NotImplementedsingleton when they cannot handle the other operand, so Python tries the reflected method (__radd__) and finally raisesTypeError. - Implicit invocation looks the method up on the type, not on the instance: setting
obj.__len__on an instance does not changelen(obj). - Defining
__eq__without__hash__sets__hash__toNone, which makes instances unhashable. - You implement dunders, you rarely call them directly: use
len(x)notx.__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__.