Magic Methods

Magic Methods are special methods in Python that start and end with double underscores.

They are also called Dunder Methods (Double Under methods).

Example:
__init__, __str__, __len__

These methods are automatically called by Python in special situations.

Why Magic Methods are Important

  • Customize object behavior
  • Enable operator overloading
  • Control how objects behave with built-in functions
  • Improve readability and flexibility

1. __init__() – Constructor

Called automatically when an object is created.

class Student:
def __init__(self, name):
self.name = names1 = Student("Hira")

2. __str__() – String Representation

Defines what is printed when you print the object.

class Student:
def __init__(self, name):
self.name = name def __str__(self):
return f"Student Name: {self.name}"s1 = Student("Hira")
print(s1)

Without __str__(), Python prints the memory location.

3. __len__() – Length Function

Allows object to work with len().

class MyList:
def __init__(self, items):
self.items = items def __len__(self):
return len(self.items)obj = MyList([1, 2, 3])
print(len(obj))

4. __add__() – Operator Overloading

Allows objects to use + operator.

class Number:
def __init__(self, value):
self.value = value def __add__(self, other):
return Number(self.value + other.value)n1 = Number(10)
n2 = Number(5)result = n1 + n2
print(result.value)

5. __eq__() – Equality Comparison

Defines behavior for ==.

class Student:
def __init__(self, marks):
self.marks = marks def __eq__(self, other):
return self.marks == other.markss1 = Student(90)
s2 = Student(90)print(s1 == s2)

Commonly Used Magic Methods

__init__() – Constructor
__str__() – String display
__repr__() – Official representation
__len__() – Length
__add__() – Addition
__sub__() – Subtraction
__mul__() – Multiplication
__eq__() – Equality check

Key Points

  • Always use double underscores before and after
  • Automatically called by Python
  • Used to modify built-in behavior
  • Enable operator overloading

Key Takeaway

Magic Methods allow you to customize how objects behave with built-in Python operations.

They make classes powerful, flexible, and fully integrated with Python’s built-in features.

Home » OBJECT ORIENTED PROGRAMMING IN PYTHON (OOP) > Advanced OOP > Magic Methods