Implementing Core Special Methods
Initialization Special Methods
__init__
Method
The __init__
method is used to initialize object attributes when an instance is created.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student = Student("Alice", 20)
__new__
Method
__new__
is called before __init__
and is responsible for creating the instance.
class SingletonClass:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
Representation Special Methods
__str__
vs __repr__
Method |
Purpose |
Usage |
__str__ |
Human-readable representation |
print(object) |
__repr__ |
Detailed, unambiguous representation |
Direct object output |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point at ({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
Comparison Special Methods
Implementing Comparison Operators
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def __eq__(self, other):
return self.area() == other.area()
def __lt__(self, other):
return self.area() < other.area()
rect1 = Rectangle(3, 4)
rect2 = Rectangle(2, 6)
print(rect1 == rect2) ## False
print(rect1 < rect2) ## True
Container and Sequence Special Methods
Key Container 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
def __iter__(self):
return iter(self._items)
custom_list = CustomList([1, 2, 3])
print(len(custom_list)) ## 3
print(custom_list[1]) ## 2
Arithmetic Special Methods
Implementing Custom Arithmetic 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)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
result = v1 + v2
scaled = v1 * 3
print(result) ## Vector(4, 6)
print(scaled) ## Vector(3, 6)
Special Method Workflow
graph TD
A[Object Creation] --> B[__new__]
B --> C[__init__]
C --> D{Object Operations}
D --> |Comparison| E[__eq__, __lt__, etc.]
D --> |Arithmetic| F[__add__, __mul__, etc.]
D --> |Container| G[__len__, __getitem__, etc.]
D --> |Representation| H[__str__, __repr__]
Best Practices
- Implement methods that make sense for your class
- Follow Python's conventions and expectations
- Keep implementations simple and predictable
- Test your special methods thoroughly
By mastering these core special methods, you can create more powerful and intuitive classes in Python, leveraging the language's dynamic capabilities with LabEx's recommended practices.