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
class Bike:
    def __init__(self, number, rate):
        self.number = number
        self.rate = rate

    def __str__(self):
        return f"Bike {self.number}"

    def __repr__(self):
        return f"Bike({self.number}, {self.rate})"

print(Bike(7, 4), [Bike(7, 4)])

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