What are Dunder Methods?
Dunder methods (double underscore methods) define how objects behave with built-in operations. They're also called "magic methods".
Common Dunder Methods
Most commonly used methods:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
def __repr__(self):
return f"Person('{self.name}', {self.age})"
def __len__(self):
return len(self.name)
person = Person("Alice", 30)
print(person) # Uses __str__
print(len(person)) # Uses __len__
Comparison Methods
Define how objects compare:
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
def __lt__(self, other):
return (self.x**2 + self.y**2) < (other.x**2 + other.y**2)
Arithmetic Methods
Define mathematical operations:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
Important Methods
__init__: Object initialization__str__: String representation (user-friendly)__repr__: String representation (developer-friendly)__len__: Length of object__getitem__: Indexing support__call__: Make object callable
Best Practices
- Implement __str__ and __repr__: Makes debugging easier
- Use appropriate methods: Only implement what you need
- Follow conventions: __repr__ should be unambiguous
- Document methods: Explain what each dunder method does
Next Steps
Learn about dataclasses and @property.