Implementing Magic Methods
Understanding Magic Methods
Magic methods, also known as dunder methods (double underscore), are special methods in Python that provide a way to define how objects behave with built-in operations and syntax.
Core Magic Methods Categories
graph TD
A[Magic Methods] --> B[Initialization]
A --> C[Representation]
A --> D[Comparison]
A --> E[Arithmetic Operations]
A --> F[Container Methods]
Initialization Magic Methods
__init__() Method
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
__new__() Method
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
Representation Magic Methods
| Method |
Purpose |
Example |
__str__() |
Human-readable string representation |
print(object) |
__repr__() |
Detailed string representation |
repr(object) |
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})"
Comparison Magic Methods
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __eq__(self, other):
return self.width * self.height == other.width * other.height
def __lt__(self, other):
return self.width * self.height < other.width * other.height
Arithmetic Operation Magic Methods
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)
Container Magic Methods
class CustomList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
def __getitem__(self, index):
return self.items[index]
def __setitem__(self, index, value):
self.items[index] = value
Advanced Magic Methods
Context Management
class FileManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'r')
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
Best Practices
- Implement methods that make sense for your class
- Follow Python's conventions and expectations
- Ensure consistent and predictable behavior
- Use type checking when necessary
Common Pitfalls
- Overcomplicating magic method implementations
- Unexpected side effects
- Performance considerations
LabEx recommends mastering magic methods to create more powerful and intuitive Python classes.