Python is a versatile language that has multiple features to perform a various array of tasks from basic programming to performing complex machine learning tasks. Now if we talk about the magic method, this is also one of the powerful tools to customize the class behavior in Python. It is also called as dunder(double underscore) method as these are the special methods that are surrounded by double underscores(e.g.,__init__,__str__) that enable you to define how your custom classes work when certain operations are performed on them. Let us dive into the blog to understand in detail about these magic methods and what they can do.
Table of Contents:
What is a Magic Method in Python?
In the beginning, we learned that the magic method in Python is the special method that is surrounded by double underscores. These methods are the predefined methods that allow the objects to have some specific behaviors. These are mostly used to perform an operation called overloading as well as arithmetic operations(addition, subtraction), comparison operations, string representation, etc. Magic methods are called implicitly by Python and thus provide a way to integrate custom objects smoothly into the Python environment.
Controlling the Object Creation Process
- Object initialization: __init__
The __init__ method is used to initialize the object’s attributes when an instance of the class is created.
Now let us understand the same thing with an example:
class Student:
def __init__(self, name, course):
self.name = name
self.course = course
student = Student("Ashna", “Data Science”)
print(student.name)
#output:
Ashna
The __init__ method assigns the values “Ashna” and “Data Science” to the name and course, respectively. When the student object is created, these attributes are initialized automatically.
- Creating Objects: __new__():
The __new__() is a special method that is used for creating an instance of a class. It is mostly called before the __init__() method and is mostly used when you want to control the creation process of an object, like when you are dealing with immutable objects such as tuples and strings.
Now let us take an example:
class Customized:
def __new__(cls, *args, **kwargs):
print("We are now creating the instance...")
#calling of the parent class
instance = super().__new__(cls)
__new__()
return instance
def __init__(self, value):
print("Initializing your instance...")
self.number = number
obj = Customized(93)
print(obj.number)
Shape Your Career in Data Science
Grow with Our Data Science Training
Representing Objects as Strings
- __str__():
It is used to define a user-friendly representation of an object. It gives you human-readable output when you are printing the object. Python uses this method internally when you are calling the str() function using an instance of the class, which is passed as an argument.
Let us take an example of the same:
class Student:
def __init__(self, course, marks):
self.course = course
self.marks = marks
def __str__(self):
return f"Student(course={self.course}, marks={self.marks})"
student = Student("Data Science", 70)
print(student)
- __repr__():
It is used to define a string representation of an object. If you print an object or inspect it in a Python interactive shell, this method is used to decide the output displayed. This makes it easier to debug by giving meaningful results about an object.
For example:
class Student:
def __init__(self, course, marks):
self.course = course
self.marks = marks
def __repr__(self):
return f"Student(course='{self.course}', marks={self.marks})"
# Example usage
student = Student("Data Science", 80)
print(student)
Output:
Student(course='Data Science', marks=80)
Supporting Operator Overloading in Custom Classes
Arithmetic Operators
Magic method for arithmetic operators lets you understand how objects in your class answer to mathematical operations. Below is a list of operators along with the magic method and an example of how you can use it.
Operator |
Magic Method |
+ |
__add__() |
– |
__sub__() |
* |
__mul__() |
/ |
__truediv__() |
// |
__floordiv__() |
% |
__mov__() |
** |
__pow__() |
Let us under by taking some examples:
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)
vector1 = Vector(1, 2)
vector2 = Vector(3, 4)
print(vector1 +vector2)
The __add__() method allows the + operator to add two Vector objects. It returns a new Vector with the summed x and y values.
Comparison Operator Methods
This method gives results about how the objects are compared:
Operator |
Magic Method |
== |
__eq__(self, other) |
!= |
__ne__(self, other) |
< |
__lt__(self, other) |
<= |
__le__(self, other) |
> |
__gt__(self, other) |
>= |
__ge__(self, other) |
Examples:
class Student:
def __init__(self, course, marks):
self.course = course
self.marks = marks
def __lt__(self, other):
return self.marks < other.marks
# Usage
student1 = Student("Data Science", 80)
student2 = Student("Discrete Mathematics", 90)
print(student1 < student2)
Output:
True
Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
Magic methods in Python enable you to add custom behavior to your classes, making objects behave like built-in types by overriding methods such as __str__, __len__, or __add__. In Python, magic methods allow you to define how objects interact with operators, customize string representations, and make containers. Using these methods adds a “magic” touch to your code, enabling intuitive, Pythonic design, and once mastered, their proper use is all practice.