The 6 AI Engineering Patterns, come build with Greg live: Starts Jan 6th, 2025
Leverage
Glossary

Double Underscore (Dunder)

Add dunder methods to Python classes

In Python, you can enrich your classes with dunder methods. These are considered magic or special methods. Although, they aren’t as unique as you may think.

They are easy to spot because they start and end with double underscores, hence where the ‘dunder’ name comes from. For example, __init__ or __name__. You can treat them like regular functions in normal python.

Dunder methods let you add extra properties to your classes. For example, len() in python will return the length of something to you, however, this functionality isn’t supported out of the box with classes.

But if you add a __len__ dunder to your class, then you’ll be able to use len(your_class).

class Student:
    def __init__(self):
        self.num_tests = 10  	
  
    def __len__(self):
        return self.num_tests

bob = Student()
len(bob)
>>> 10

The list of common dunders within classes include:

  • __init__: This constructor takes care of the basics. It helps set up the object
  • __str__: The ‘nice’ version of the printed object. This is a human readable format to print
  • __repr__: The ‘official’ string of the object. This is what will print when you return the object
  • __len__: The method that runs when you call len() on your object
  • __getitem__: You’ll be able to return a specific item (if you have a list of them) within your object
  • __getattr__: A ‘catcher’. If you try calling an attr that doesn’t exist, this function will return a value you set. If it does exist, it will do nothing.
  • __reversed__: Only applicable if you have __len__ and __getitem__. This will return the reverse of items that you set

Let’s take a look at a python dunder code sample.

Link to code

On this page

No Headings