Part 4 · Section 04

Polymorphism and Special Methods

Why does len(x) work on a list, a string and a dictionary? Why can you write a + b for numbers, strings and lists alike? The answer is polymorphism through special methods: Python’s syntax and built-in functions don’t care what type an object is, they just call a method with a reserved double-underscore name. Define that method in your class and your objects join in, so they print nicely, add, compare, work as dictionary keys, behave in if statements and can even be called like functions.

In this section you’ll learn:

Lectures

  1. 01__str__ and __repr__ Methods✓
  2. 02Arithmetic Operators✓
  3. 03Rich Comparisons✓
  4. 04Hashing and Equality✓
  5. 05Booleans✓
  6. 06Callables✓
  7. 07The __del__ Method✓
  8. 08The __format__ Method✓

Practice: quiz & exercises

12 quiz questions · 4 coding exercises

Go to practice →