Implementing Core Methods
Initialization Methods
__init__
Method
The primary constructor for creating and initializing object instances.
class User:
def __init__(self, name, age):
self.name = name
self.age = age
__new__
Method
Used for advanced object creation and customization.
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
Representation Methods
__str__
vs __repr__
Method |
Purpose |
Usage |
__str__ |
Human-readable representation |
Used by str() function |
__repr__ |
Detailed, unambiguous representation |
Used by repr() function |
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __str__(self):
return f"{self.name}: ${self.price}"
def __repr__(self):
return f"Product(name='{self.name}', price={self.price})"
Comparison Methods
Implementing Comparison Operations
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 Methods
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)
Container Methods
Implementing Container-like Behavior
class CustomList:
def __init__(self):
self._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
Method Invocation Flow
graph TD
A[Method Call] --> B{Magic Method Defined?}
B -->|Yes| C[Execute Custom Implementation]
B -->|No| D[Use Default Python Behavior]
LabEx Practical Tip
At LabEx, we emphasize understanding the context and purpose of each magic method to write more efficient and pythonic code.
Key Considerations
- Always return appropriate types
- Maintain consistent behavior
- Handle edge cases
- Follow Python's convention and expectations