DEV Community

Cover image for Quark's Outlines: Python Special Method Names
Mike Vincent
Mike Vincent

Posted on

Quark's Outlines: Python Special Method Names

Quark’s Outlines: Python Special Method Names

Overview, Historical Timeline, Problems & Solutions

An Overview of Python Special Method Names

What are Python special method names?

When you use built-in syntax in Python, like +, [], or len(), Python checks if the object has a matching method with a special name. These are called Python special method names. They let your class behave like other built-in types.

Each special method has a name with two underscores before and after it. For example, __add__ lets your object respond to +, and __getitem__ lets your object respond to indexing like obj[2].

Python lets classes use special method names to behave like built-in types.

class Item:
    def __getitem__(self, index):
        return index * 2

x = Item()
print(x[3])
# prints:
# 6
Enter fullscreen mode Exit fullscreen mode

When you use x[3], Python runs x.__getitem__(3) because the class defined that method.

Why use Python special method names?

You use special method names to give your object custom behavior when used in common expressions. You can define how your object adds, subtracts, prints, or compares. These names give you control without writing extra code for every case.

You do not call special methods directly in normal code. Python calls them for you when your object is used with special syntax.

Python calls special method names automatically when using common syntax.

class Greeter:
    def __str__(self):
        return "Hello!"

g = Greeter()
print(g)
# prints:
# Hello!
Enter fullscreen mode Exit fullscreen mode

The print() function uses str(g), which calls g.__str__() to get the string value.


A Historical Timeline of Python Special Method Names

Where do Python’s special method names come from?

Python special method names come from earlier object models that used hidden function calls to support operators and custom syntax. Python exposed those methods with a clear naming pattern so users could build objects that act like built-ins.


People created ways to override behavior in custom types

1970 —Simula and Smalltalk introduced object methods to control print, math, and access.

1983 —C++ operator overloading let programmers define how +, ==, and [] work for their own classes.


People added readable hooks to Python objects

1991 —Python object model introduced dunder methods (like __getitem__) to let user-defined classes support special syntax.

2000 —New-style classes in Python 2.2 unified the object model, making all types use special methods.

2013 —Function annotations and class introspection used __annotations__, __class__, and other internal names.

2025 —Stable core dunder names became essential for all custom types and data classes, with no new names added in recent releases.


Problems & Solutions with Python Special Method Names

How do you use Python special method names the right way?

Python special method names let your class support syntax that feels natural. These problems show how to use them to add math, indexing, string conversion, length, and iteration to your custom classes. Each solution shows how Python lets you control behavior using the correct special method.


Problem: How do you support + for your object in Python?

You are making a custom class that holds a number. You want to let users add two of your objects with the + symbol, the same way they add numbers. But Python does not know how to add your objects unless you tell it how.

Problem: You want your class to support +.

Solution: Python calls __add__() when two objects are added.

Python lets you define __add__() to support +.

class Box:
    def __init__(self, value):
        self.value = value
    def __add__(self, other):
        return Box(self.value + other.value)
    def __str__(self):
        return str(self.value)

a = Box(5)
b = Box(3)
c = a + b
print(c)
# prints:
# 8
Enter fullscreen mode Exit fullscreen mode

The method __add__() lets your class handle +. The result is another Box with the new total.


Problem: How do you make your object show custom text with print() in Python?

You want your object to show a friendly message when someone prints it. By default, Python shows the memory address. You want it to show a message instead.

Problem: You want your object to return a message when printed.

Solution: Python uses __str__() to get the string for print().

Python lets you define __str__() to control how objects print.

class Pet:
    def __str__(self):
        return "This is your pet."

p = Pet()
print(p)
# prints:
# This is your pet.
Enter fullscreen mode Exit fullscreen mode

The __str__() method lets you return a string that print() will show.


Problem: How do you let your object be used like a list in Python?

You made a custom data class. You want people to use square brackets [] to get values, just like with lists. But Python does not know how unless you define a method.

Problem: You want your object to support indexing.

Solution: Python calls __getitem__() when using brackets.

Python lets you define __getitem__() to allow square bracket access.

class Pair:
    def __getitem__(self, i):
        return ["left", "right"][i]

p = Pair()
print(p[1])
# prints:
# right
Enter fullscreen mode Exit fullscreen mode

The __getitem__() method lets your object handle p[1] like a list or string.


Problem: How do you let your object work with len() in Python?

You want your class to tell how many items it holds. You want to use len(obj), but Python cannot do that unless your object supports it.

Problem: You want to let len(obj) work with your object.

Solution: Python calls __len__() when you use len().

Python lets you define __len__() to support length checks.

class Trio:
    def __len__(self):
        return 3

t = Trio()
print(len(t))
# prints:
# 3
Enter fullscreen mode Exit fullscreen mode

This method makes len(t) return 3 because you defined it that way.


Problem: How do you make your object work in a for-loop in Python?

You want users to loop over your object with for x in obj:. Right now Python does not know how. You want to return one value at a time from inside your object.

Problem: You want your object to be used in a loop.

Solution: Python uses __iter__() and __next__() to support loops.

Python lets you define __iter__() to support iteration.

class CountDown:
    def __init__(self, start):
        self.current = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for n in CountDown(3):
    print(n)
# prints:
# 3
# 2
# 1
Enter fullscreen mode Exit fullscreen mode

When used in a loop, Python runs __iter__() to get the object and calls __next__() to get each value.


Like, Comment, Share, and Subscribe

Did you find this helpful? Let me know by clicking the like button below. I'd love to hear your thoughts in the comments, too! If you want to see more content like this, don't forget to subscribe. Thanks for reading!


Mike Vincent is an American software engineer and app developer from Los Angeles, California. More about Mike Vincent

Top comments (0)