Academic Block

Python Special (Dunder) MethodsGet Certified

What Are Special (Dunder) Methods?

Special methods, also called dunder methods (short for “double underscore”), are methods with names that begin and end with two underscores. Python calls them automatically in response to built-in operations. When you write print(obj), Python looks for obj.__str__(). When you write len(obj), it looks for obj.__len__(). By defining these methods you make your own classes behave like the built-in types. This is one of the most powerful features of object-oriented Python and the foundation of operator overloading, custom containers, and clean printable objects.

  • Automatic calls: Python invokes them for you when certain syntax is used.
  • Consistent interface: your objects can work with print, len, +, ==, and more.
  • Readable code: clients use natural operators instead of method calls.
  • Common names: __init__, __str__, __repr__, __len__, __eq__, __add__.

Making Objects Print Nicely with __str__ and __repr__

By default, printing an object shows a technical memory address that is rarely useful. Defining __str__ gives a human-friendly description for print() and str(). Defining __repr__ gives an unambiguous representation that is ideal for debugging and for the interactive prompt. A good rule is that __repr__ should, if possible, look like a valid Python expression that recreates the object. Many classes implement both methods.

Try It: A Book That Prints Cleanly

Click Test My Code. Change the title or author and watch both the friendly and the official representations update.

What this code does: A Book class stores a title and an author. __str__ produces a readable sentence while __repr__ produces a string that looks like a constructor call. Both are demonstrated.
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f'"{self.title}" by {self.author}'

    def __repr__(self):
        return f'Book("{self.title}", "{self.author}")'

b = Book("To Kill a Mockingbird", "Harper Lee")
print(str(b))
print(repr(b))
print(b)

Operator Overloading with __add__ and Friends

Python lets you redefine what the operators +, -, *, and others mean for your own classes. You do this by implementing methods such as __add__, __sub__, and __mul__. When the interpreter sees a + b, it tries to call a.__add__(b). This technique is called operator overloading. It makes custom numeric types, vectors, and money classes feel natural to use.

Try It: Adding Two Money Amounts

Click Test My Code. Change the dollar amounts and confirm that addition still works.

What this code does: A Money class stores an amount in dollars. The __add__ method lets two Money objects be added with the + operator. The result is a new Money object.
class Money:
    def __init__(self, dollars):
        self.dollars = dollars

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

    def __str__(self):
        return f"${self.dollars:.2f}"

paycheck = Money(1850.00)
bonus = Money(250.00)
total = paycheck + bonus
print(total)

Making Objects Act Like Sequences

If your class represents a collection, you can make it work with len(), indexing, and for loops by implementing a few special methods. __len__ is called by len(). __getitem__ is called when an index or a slice is requested. Once these methods exist, many built-in functions and constructs treat your object as a sequence.

Try It: A Playlist That Supports len() and Indexing

Click Test My Code. Try changing the index or adding another song and watch the results.

What this code does: A Playlist class holds a list of song titles. __len__ reports how many songs are present and __getitem__ returns the song at a given position. Both built-in operations are demonstrated.
class Playlist:
    def __init__(self, songs):
        self.songs = list(songs)

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

    def __getitem__(self, index):
        return self.songs[index]

    def __str__(self):
        return f"Playlist with {len(self)} songs"

mix = Playlist(["Shake It Off", "Blank Space", "Love Story"])
print(len(mix))
print(mix[1])
print(mix)

Comparison Methods: __eq__, __lt__, and More

By default, two objects of a custom class are equal only if they are the exact same object in memory. Defining __eq__ lets you decide when two instances should be considered equal. Defining __lt__ (less than) enables sorting. Once you provide a few comparison methods, Python can fill in the rest with the @total_ordering decorator from the functools module, but the basic versions are enough for most needs.

Try It: Comparing Students by GPA

Click Test My Code. Change the GPA values and observe how equality and ordering behave.

What this code does: A Student class stores a name and a GPA. __eq__ treats two students as equal when their GPAs match. __lt__ allows sorting by GPA. The results of both comparisons are shown.
class Student:
    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa

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

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

    def __str__(self):
        return f"{self.name} ({self.gpa})"

s1 = Student("Maya Patel", 3.8)
s2 = Student("Noah Brooks", 3.8)
s3 = Student("Liam Torres", 3.5)
print(s1 == s2)
print(s3 < s1)
print(sorted([s1, s3, s2]))

Making Objects Callable with __call__

Sometimes an object should behave like a function. Defining the __call__ method lets you write obj(arguments) instead of obj.method(arguments). Callable objects are useful for stateful functions, configurable processors, and simple callbacks. The technique keeps the call site clean while still allowing the object to remember information between calls.

Try It: A Multiplier That Remembers Its Factor

Click Test My Code. Create another multiplier with a different factor and test it.

What this code does: A Multiplier class stores a numeric factor. Calling an instance multiplies that factor by the supplied value. The object can be used exactly like a function.
class Multiplier:
    def __init__(self, factor):
        self.factor = factor

    def __call__(self, value):
        return self.factor * value

double = Multiplier(2)
triple = Multiplier(3)
print(double(15))
print(triple(15))
print(double(7) + triple(4))

Context-Manager Protocol: __enter__ and __exit__

The with statement is one of Python’s most useful features for managing resources. Any object that implements __enter__ and __exit__ can be used as a context manager. __enter__ is called when the block is entered and usually returns the object that will be bound to the as variable. __exit__ is called when the block ends, even if an exception occurred, and is responsible for cleanup.

Try It: A Simple Timer Context Manager

Click Test My Code. The timer measures how long the block takes and prints the result automatically.

What this code does: A Timer class records the start time in __enter__ and the end time in __exit__. When the with block finishes, the elapsed time is printed. No manual start or stop calls are required.
import time

class Timer:
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        print(f"Elapsed: {self.end - self.start:.4f} seconds")
        return False

with Timer():
    total = sum(range(1_000_000))
print("Calculation finished")

Putting Several Dunder Methods Together

Real classes often implement many special methods at once. A well-designed class might support printing, comparison, addition, and length. The goal is always the same: make the object feel natural to other Python programmers. When the special methods are consistent, client code becomes short, readable, and free of type checks.

Try It: A Vector That Supports Math and Printing

Click Test My Code. Try adding different vectors or changing the coordinates.

What this code does: A two-dimensional Vector class implements __init__, __str__, __repr__, __add__, and __eq__. The demonstration shows creation, addition, equality testing, and printing.
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Vector({self.x}, {self.y})"

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

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

v1 = Vector(3, 4)
v2 = Vector(1, 2)
v3 = v1 + v2
print(v3)
print(v3 == Vector(4, 6))

Common Mistakes with Dunder Methods

Special methods are powerful, yet a few recurring mistakes can make them fail silently or produce confusing results. The list below covers the problems that appear most often when students first implement these methods.

  • Forgetting to return a value: __str__, __add__, and most other dunder methods must return a result; a missing return produces None.
  • Returning the wrong type: __add__ should normally return a new instance of the same class, not a plain number or string.
  • Ignoring the other operand: comparison and arithmetic methods receive another object; always check or convert it carefully.
  • Implementing only __eq__: without __hash__ (or by setting it to None), objects that compare equal cannot be used safely in sets or as dictionary keys.
  • Making __repr__ expensive: the interactive prompt calls __repr__ often; keep it fast and free of side effects.
  • Forgetting __exit__ cleanup: resources opened in __enter__ must be released in __exit__, even when an exception occurs.

Key Takeaways

Special methods let your classes participate in the same syntax that Python programmers already know. They turn custom objects into first-class citizens of the language. The points below summarize the most important ideas you will use again and again.

  • Dunder methods are called automatically by Python for operators, built-in functions, and language constructs.
  • __str__ produces a human-friendly description; __repr__ produces an unambiguous, ideally evaluable representation.
  • Operator overloading is achieved by implementing methods such as __add__, __sub__, and __mul__.
  • __len__ and __getitem__ make an object behave like a sequence.
  • __eq__ and __lt__ enable equality tests and sorting.
  • __call__ turns an instance into a callable object.
  • __enter__ and __exit__ support the with statement for clean resource management.

Frequently Asked Questions

The questions below are the ones students ask most often when they first encounter special methods. Each answer is short and practical, and each idea appears in one of the examples above. Experiment with the live code boxes to confirm the behavior for yourself.

What is a dunder method in Python?

A dunder method (short for “double underscore”) is a special method whose name begins and ends with two underscores. Python calls these methods automatically for operators, built-in functions, and language features such as printing and the with statement.

What is the difference between __str__ and __repr__?

__str__ is meant for end users and is used by print() and str(). __repr__ is meant for developers and is used by the interactive prompt and by repr(). A good __repr__ should, if possible, look like a valid Python expression that recreates the object.

How do I make the + operator work with my class?

Implement the __add__ method. When Python sees a + b it calls a.__add__(b). The method should normally return a new instance of your class.

How can my object support len() and indexing?

Define __len__ to return the number of items and __getitem__ to return the item at a given index. Once these methods exist, many built-in functions treat the object as a sequence.

What does __call__ do?

Defining __call__ lets you use an instance as if it were a function: obj(arguments). This is useful for stateful callables and configurable processors.

How do I make my class work with the with statement?

Implement __enter__ (called when the block starts) and __exit__ (called when the block ends). __exit__ receives information about any exception that occurred and should perform cleanup.

Do I need to implement every comparison method?

No. Implementing __eq__ and __lt__ is often enough. The functools.total_ordering decorator can generate the remaining rich comparison methods for you if you wish.

Why does my object still show a memory address when printed?

Python falls back to the default representation when __str__ and __repr__ are missing. Define at least one of them to control what appears.

Ready for the next step?Learn how to write clean, reusable functions that wrap other functions.
Next: Decorators →