Paul's Python CoursePPC

Dunder methods

Not met yet

Dunder (double underscore) methods are the ones Python calls for you. __str__ is what print and str() show to people; __repr__ is the programmer's version, used inside lists and when there's no __str__. __eq__ decides ==: return NotImplemented for things you can't compare. __len__ answers len().

Try it

main.py

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks a list shows its items with __str__ rather than __repr__.
  • Thinks print uses __repr__ even when the class defines __str__.
  • Thinks dunder methods do nothing unless they are called by name.
  • Thinks two objects with the same attributes are == even without an __eq__ method.
  • Thinks a method that ends without a return statement gives False rather than None.

Where it comes up