What Are Dunder Methods in Python: Explanation and Examples
dunder methods are special methods with double underscores before and after their names, like __init__ or __str__. They let you customize how objects behave with built-in operations such as creation, printing, or arithmetic.How It Works
Dunder methods, short for "double underscore" methods, are like secret codes that Python looks for to perform special actions on objects. Imagine them as hidden switches inside your objects that tell Python how to handle things like creating an object, printing it, or comparing it to another.
For example, when you create a new object, Python automatically calls the __init__ method to set it up. When you print an object, Python looks for the __str__ method to decide what text to show. These methods let you control how your objects behave in everyday tasks, making your code more natural and powerful.
Example
This example shows a simple class with two dunder methods: __init__ to set up the object and __str__ to define what prints when the object is shown.
class Dog: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Dog named {self.name}, aged {self.age} years" my_dog = Dog("Buddy", 5) print(my_dog)
When to Use
Use dunder methods when you want your objects to work smoothly with Python’s built-in features. For example, if you want to create objects that can be added together, compared, or printed nicely, you define the right dunder methods.
Real-world uses include customizing how data models display information, making classes that behave like numbers or collections, or controlling object creation and cleanup. They help your classes feel like natural parts of Python.
Key Points
- Dunder methods have names with double underscores before and after, like
__init__. - They let you customize object behavior for built-in operations.
- Common dunder methods include
__str__,__repr__,__add__, and__eq__. - Using them makes your classes integrate naturally with Python features.