Python 3D Academyবাংলা

Dunder Methods in Python

Chapter 24: Dunder Methods

6 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. __str__ and __repr__: objects that print nicely

    str decides what print(obj) shows to people, and repr gives an exact, code-like description for programmers.

  2. __eq__ and __lt__: comparing objects

    eq teaches == what "equal" means for your class, and lt teaches <, which also makes sorted, min and max work.

  3. __len__, __getitem__ and __contains__: objects that hold things

    len, getitem and contains let your class answer len(x), x[i] and item in x, just like a list.

  4. __add__ and __mul__: your own + and *

    add and mul let + and * work on your objects, and each should build and return a new object.

  5. __hash__: objects in sets and as dict keys

    A set or dict first asks hash(x) for a number that says where to look, and only then uses == on the few items found there, so objects that are equal must have equal hashes.

  6. __call__ and __bool__: objects you can call, and objects that are true or false

    call lets you call an object like a function, obj(x), using the settings in its fields; bool decides whether the object counts as True or False in if, while and bool().