QABash Community Forum

Please or Register to create posts and topics.

What do __double_underscores__ mean in Python?

In Python, when you see names with double underscores (like __init__, __str__, or even __name__), they serve special purposes.


What do __double_underscores__ mean?

Names with double underscores before and after (also called "dunder methods") are special or magic methods used by Python behind the scenes.

They’re part of Python’s object-oriented features and allow you to customize how your objects behave.


Examples of Common __dunder__ Methods:

Dunder Method What It Does
__init__() Called when you create a new object (constructor)
__str__() Called when you use print() on an object
__repr__() Called when you use repr() or in debugging
__len__() Makes your object work with len()
__getitem__() Lets you use square brackets [] like a list
__name__ A built-in variable to check if script is run directly or imported

✨ Example:

class Dog:
def __init__(self, name):
self.name = name

def __str__(self):
return f"This is a dog named {self.name}."

dog = Dog("Buddy")
print(dog)

Output:

This is a dog named Buddy.

Here, __init__() sets the name, and __str__() defines how the object looks when printed.


What about names like __secret_var?

These usually indicate name mangling, where Python changes the name slightly to avoid accidental access or override (often used in classes for "private" variables).


πŸ” Tip:

Not all double underscore names are meant for you to define. Stick to ones documented in the official Python docs unless you're customizing behavior intentionally.

Scroll to Top
×