Magic Methods in Python

Python 10 min min read Updated: Mar 09, 2026 Advanced
Magic Methods in Python
Advanced Topic 2 of 10

Magic Methods in Python

Magic methods in Python are special methods that start and end with double underscores (__). These methods are also known as dunder methods (double underscore methods). They allow developers to define how objects behave when interacting with built-in Python operations such as addition, comparison, printing, and more.

Magic methods are widely used in Object-Oriented Programming (OOP) to customize the behavior of objects and make classes behave like built-in Python data types.

What are Magic Methods?

Magic methods are automatically invoked by Python when certain operations are performed on objects. For example, when you add two numbers using the + operator, Python internally calls a magic method.

Example:

python class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value num1 = Number(10) num2 = Number(20) print(num1 + num2)

Here, the __add__() method defines how objects behave when the + operator is used.

Common Magic Methods

Python provides many built-in magic methods. Some commonly used ones include:

Magic Method Description
__init__ Constructor method called when an object is created
__str__ Defines string representation of an object
__repr__ Returns official string representation
__len__ Returns the length of an object
__add__ Defines addition behavior
__sub__ Defines subtraction behavior
__eq__ Defines equality comparison
__lt__ Defines less-than comparison

The __init__ Method

The __init__() method is the constructor that initializes object attributes.

python class Person: def __init__(self, name): self.name = name person = Person("Alice") print(person.name)

The __str__ Method

The __str__() method defines how an object is displayed when printed.

python class Book: def __init__(self, title): self.title = title def __str__(self): return f"Book title: {self.title}" book = Book("Python Basics") print(book)

This method provides a readable representation of the object.

The __repr__ Method

The __repr__() method returns an official string representation of the object, often used for debugging.

python class Product: def __init__(self, name): self.name = name def __repr__(self): return f"Product('{self.name}')" product = Product("Laptop") print(product)

The __len__ Method

The __len__() method allows objects to work with the len() function.

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

Operator Overloading

Magic methods allow operator overloading, which means redefining how operators behave for custom objects.

python class Vector: def __init__(self, x): self.x = x def __add__(self, other): return Vector(self.x + other.x) v1 = Vector(5) v2 = Vector(3) result = v1 + v2 print(result.x)

This allows objects to behave like numeric values.

Comparison Magic Methods

Magic methods also control comparison operations.

python class Student: def __init__(self, marks): self.marks = marks def __gt__(self, other): return self.marks > other.marks s1 = Student(80) s2 = Student(70) print(s1 > s2)

The __gt__() method defines the behavior of the greater-than operator.

Real-World Example

Magic methods are often used in frameworks, libraries, and data models.

python class User: def __init__(self, username): self.username = username def __str__(self): return f"User: {self.username}" user = User("john123") print(user)

This provides a clean representation when printing user objects.

Best Practices for Using Magic Methods

  • Use magic methods only when necessary.
  • Ensure custom behavior remains intuitive.
  • Follow Python naming conventions.
  • Avoid overriding too many operators unnecessarily.

Conclusion

Magic methods are a powerful feature of Python that allow developers to customize object behavior and integrate classes seamlessly with Python’s built-in operations. By using magic methods such as __init__, __str__, and __add__, developers can create flexible and intuitive class designs.

Understanding magic methods is essential for mastering advanced Python programming and building professional-level libraries and frameworks.

In the next tutorial, we will explore Python Iterators and Generators and understand how Python handles lazy evaluation and efficient data processing.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators