SOARDO
Software Engineer (SDE)pythonintermediate3 interactive MCQs in app

Magic/Dunder Methods (__str__, __len__, __eq__)

__repr__ vs __str__ developer vs display__eq__ and __hash__ contractreturning NotImplemented for mismatched types

Magic (dunder) methods hook custom classes cleanly into Python’s built-in syntax: `__repr__` gives developers an unambiguous debug representation (fallback if `__str__` is absent); `__len__` powers `len(obj)`; `__eq__` + `__hash__` govern `==` and `set`/`dict` membership cleanly! Rule: if two objects compare equal (`a == b`), they MUST have identical `__hash__` (`hash(a) == hash(b)`)—implementing custom `__eq__` without `__hash__` automatically sets `__hash__ = None` making objects unhashable!

defining `def __len__(self): return len(self._tracks)` and `def __iter__(self): return iter(self._tracks)` lets callers write `len(playlist)` and `for t in playlist` cleanly!
returning `False` instead of `NotImplemented` in `__eq__` for unrelated types, or mutating hashed fields after insertion into a `set`.
Python Magic Methods — Real Pythonread ↗Magic/Dunder Methods (__str__, __len__, __eq__) — Applied Practicepractice ↗Exercism Python Track (Interactive)practice ↗

Practice Magic/Dunder Methods (__str__, __len__, __eq__) with 3 graded MCQs & written feedback.

Take SOARDO’s free 12-question diagnostic to see how strong you are across your target role and unlock adaptive daily missions.

Test yourself free on SOARDO →View full Software Engineer roadmap

More Software Engineer Study Guides