Common Use Cases of Python Magic Methods

Common Use Cases of Python Magic Methods

1. Constructor and Initialization Methods

1. <span>__init__</span> – Initialization Method

Function: Initializes attributes after the object is createdExample:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)
print(p.name)  # Output: Alice

2. <span>__new__</span> – Instance Creation Method

Function: Controls the object creation process, commonly used in singleton patternsExample:

class Singleton:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # Output: True

2. String Representation Methods

1. <span>__str__</span> – User-Friendly String Representation

Function: Returns a user-friendly string, used in <span>str()</span> and <span>print()</span>Example:

class Person:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return f"Person(name={self.name})"

p = Person("Bob")
print(p)  # Output: Person(name=Bob)

2. <span>__repr__</span> – Official String Representation

Function: Returns a developer-friendly string, used in <span>repr()</span> and for debuggingExample:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

p = Point(3, 4)
print(repr(p))  # Output: Point(3, 4)

3. Arithmetic Operation Methods

1. <span>__add__</span> – Addition Operation

Function: Defines the addition operation for objectsExample:

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)

v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(v3.x, v3.y)  # Output: 6 8

2. <span>__sub__</span> – Subtraction Operation

Function: Defines the subtraction operation for objectsExample:

class Vector:
    # Omitted __init__ method
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

4. Comparison Operation Methods

1. <span>__eq__</span> – Equality Comparison

Function: Defines the behavior of the <span>==</span> operatorExample:

class Student:
    def __init__(self, id):
        self.id = id
    def __eq__(self, other):
        return self.id == other.id

s1 = Student(1001)
s2 = Student(1001)
print(s1 == s2)  # Output: True

2. <span>__lt__</span> – Less Than Comparison

Function: Defines the behavior of the <span><</span> operatorExample:

class Product:
    def __init__(self, price):
        self.price = price
    def __lt__(self, other):
        return self.price < other.price

p1 = Product(29.99)
p2 = Product(39.99)
print(p1 < p2)  # Output: True

5. Container Related Methods

1. <span>__len__</span> – Length Retrieval

Function: Defines the behavior of the <span>len()</span> functionExample:

class MyList:
    def __init__(self, items):
        self.items = items
    def __len__(self):
        return len(self.items)

ml = MyList([1, 2, 3, 4])
print(len(ml))  # Output: 4

2. <span>__getitem__</span> – Index Access

Function: Defines the behavior of accessing elements via <span>[]</span>Example:

class MyList:
    # Omitted __init__ method
    def __getitem__(self, index):
        return self.items[index]

ml = MyList([10, 20, 30])
print(ml[1])  # Output: 20

6. Other Common Methods

1. <span>__call__</span> – Object Call

Function: Allows the object to be called like a functionExample:

class Calculator:
    def __call__(self, a, b):
        return a + b

calc = Calculator()
print(calc(3, 5))  # Output: 8

2. <span>__enter__</span> and <span>__exit__</span> – Context Management

Function: Defines the behavior of the <span>with</span> statementExample:

class FileHandler:
    def __init__(self, filename, mode):
        self.file = open(filename, mode)
    def __enter__(self):
        return self.file
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

with FileHandler("test.txt", "w") as f:
    f.write("Hello World")

Leave a Comment