Topic 46 of 58
Dunder Methods
Overview
Dunder (Double UNDERscore) methods, often called Magic Methods, allow your custom classes to integrate seamlessly with Python's built-in syntax. By defining methods like __add__ or __len__, you can dictate exactly how your objects behave when someone uses the + operator on them or passes them to the len() function. This is the secret behind Python's elegant expressiveness.
Syntax
python
class Vector2D:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
# Dictates what print(obj) displays
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
# Dictates behavior for the '+' math operator
return Vector2D(self.x + other.x, self.y + other.y)
v1 = Vector2D(2, 3)
v2 = Vector2D(1, 1)
# Triggers __str__
print(v1) # Output: Vector(2, 3)
# Triggers __add__, returning a new Vector object
print(v1 + v2) # Output: Vector(3, 4)Common Pitfalls
- Confusing
__str__and__repr__.__str__should return a readable, user-friendly string.__repr__is strictly for developers and debugging; it should return a raw string that looks like the exact Python code needed to recreate the object.
Interview Questions
Q:
How do you make a custom object behave like a List that can be accessed via brackets (e.g.,
obj[0])?A:
By implementing the __getitem__(self, index) dunder method, which intercepts bracket notation.
Real-World Example
Making custom objects 'hashable' so they can be stored in Sets or Dictionary keys.
example
python
class DatabaseNode:
def __init__(self, ip):
self.ip = ip
def __eq__(self, other):
# Defines how '==' works
return self.ip == other.ip
def __hash__(self):
# Allows usage in sets/dicts based on IP
return hash(self.ip)Check Your Knowledge
Test your understanding of Dunder Methods with these quick questions.