Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 60 of 70

Python special (dunder) methods: make objects behave like built-ins

Learn how __str__, __repr__, __eq__, __len__, __add__ and friends let your own Python classes work with print, ==, len(), + and sorting.

14 minObject-oriented programmingUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonAdd special methods to a class so that print, comparison, len, addition and sorting work on your objects.

After this lesson your own classes will work naturally with print, ==, len(), + and sorted().

What special methods are

Python lets you write len(items), a + b and print(x) on built-in types. Behind the scenes, each of these is turned into a method call. For example a + b becomes a.__add__(b). These methods have double underscores on each side, which is why they are called dunder methods (double underscore).

You can define them in your own class. The rule to remember is this: you rarely call them yourself. You write the normal syntax, and Python calls the special method.

Printing: __str__ and __repr__

Printing an object of a plain class gives an unhelpful result, because Python has no idea what you want to show. Define __str__ to control print and str():

python
class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def __str__(self):
        return f"{self.title} ({self.pages} pages)"

    def __repr__(self):
        return f"Book({self.title!r}, {self.pages!r})"

novel = Book("The Silent Garden", 320)
print(novel)
print(repr(novel))
print([novel])
result
The Silent Garden (320 pages)
Book('The Silent Garden', 320)
[Book('The Silent Garden', 320)]

__str__ is for readers: short and friendly. __repr__ is for developers: precise, ideally looking like the code that would rebuild the object. Python uses __repr__ when an object sits inside a list, as the last line shows. If you only have time to write one, write __repr__, since print falls back to it.

Comparing: __eq__ and __lt__

By default, == on two objects asks "are these the very same object?". Usually you want to compare the contents:

python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

print(Point(1, 2) == Point(1, 2))
print(Point(1, 2) == Point(3, 4))
result
True
False

To make objects sortable, define __lt__ ("less than"). sorted() and min() only need that one:

python
class Student:
    def __init__(self, name, mark):
        self.name = name
        self.mark = mark

    def __lt__(self, other):
        return self.mark < other.mark

    def __repr__(self):
        return f"Student({self.name!r}, {self.mark})"

group = [Student("Asha", 82), Student("Ben", 74), Student("Chloe", 91)]
print(sorted(group))
print(min(group))
result
[Student('Ben', 74), Student('Asha', 82), Student('Chloe', 91)]
Student('Ben', 74)

One caution: a class that defines __eq__ and does not define __hash__ becomes unhashable, so you cannot put its objects in sets or use them as dictionary keys. That is the right behaviour for objects that can change, and a common surprise.

Size and membership: __len__ and __contains__

A container-like class can support len() and the in operator:

python
class Shelf:
    def __init__(self):
        self.books = []

    def add(self, title):
        self.books.append(title)

    def __len__(self):
        return len(self.books)

    def __contains__(self, title):
        return title in self.books

shelf = Shelf()
shelf.add("Night Trains")
shelf.add("The Silent Garden")
print(len(shelf))
print("Night Trains" in shelf)
print("Missing Book" in shelf)
result
2
True
False

Arithmetic: __add__

You can give + a meaning for your own type. Here two money amounts add up and return a new Money object:

python
class Money:
    def __init__(self, cents):
        self.cents = cents

    def __add__(self, other):
        return Money(self.cents + other.cents)

    def __str__(self):
        return f"{self.cents // 100}.{self.cents % 100:02d}"

total = Money(250) + Money(175)
print(total)
result
4.25

Similar methods exist for - (__sub__), * (__mul__) and others. Use them only where the operator is natural: adding money is clear, but "adding" two customers is not.

Other useful ones

__getitem__ makes obj[0] work, __iter__ makes a loop over the object work, __bool__ controls truthiness, and __call__ makes an object callable like a function. You will meet some of these again in the generators lesson.

A video version of this topic is in the video course at /learn/python/.

Common mistakes

  • Returning the wrong type. __str__ must return a string, and __len__ an integer. Otherwise Python raises TypeError.
  • Printing inside __str__ instead of returning. The method should return text and leave printing to the caller.
  • Assuming __eq__ gives you sorting. Sorting needs __lt__.
  • Calling dunder methods directly. Write a + b, not a.__add__(b).
  • Comparing with an object of another type. other.x fails if other is not a point. For serious code, check the type first and return NotImplemented when it does not match.

Exercise

Write a class Temperature that stores degrees. Give it a __repr__ such as Temperature(21), an __eq__ that compares degrees, and an __add__ that returns a new Temperature with the sum. Add two temperatures, print the result and print whether Temperature(5) == Temperature(5).

Show one possible answer
python
class Temperature:
    def __init__(self, degrees):
        self.degrees = degrees

    def __repr__(self):
        return f"Temperature({self.degrees})"

    def __eq__(self, other):
        return self.degrees == other.degrees

    def __add__(self, other):
        return Temperature(self.degrees + other.degrees)

print(Temperature(20) + Temperature(1))
print(Temperature(5) == Temperature(5))
result
Temperature(21)
True

Key points

  • Special methods have double underscores on both sides, such as __str__, and Python calls them for you in response to syntax and built-in functions.
  • __str__ controls print() and str(), while __repr__ gives an unambiguous form for developers.
  • __eq__ defines ==, and __lt__ lets objects be compared and sorted.
  • __len__ makes len() work, and __add__ makes + work.
  • You almost never call a special method by name. You use the syntax or function that triggers it.

Check yourself

1. Which special method does print(obj) use to get text?
2. What does defining __eq__ change?
3. What must __len__ return for len(obj) to work?
4. How do you normally use __add__?