This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: Magic methods

Magic/dunder methods

face Josiah Wang

You will probably not use magic methods much (apart from __init__()), but they might be useful when you need them!

There are more magic methods listed in the official Python documentation. For example, you can even make your classes act like a sequence with these magic methods:

  • __len__()
    • len(your_obj) invokes your_obj.__len__()
  • __contains__()
    • item in your_obj invokes your_obj.__contains__(item)
  • __getitem__()
    • your_obj[key] invokes your_obj.__getitem__(key)
  • __setitem__()
    • your_obj[key] = item invokes your_obj.__setitem__(key, item)
  • __iter__() allows you to use your class as iterators in for loops

We will not be implementing these, as these are quite advanced stuff! But it’s good to know that you can do these if you ever need to!