Python Magic Methods
Magic methods, also known as dunder methods, are special methods that are used to define behavior for certain operations or behaviors that are built into the language. They are denoted by double underscores on both sides of the method name.
Here are some common dunder methods and their usage:
Get Badal Panwar’s stories in your inbox
Join Medium for free to get updates from this writer.
__init__ is used to initialize the attributes of an object when it is created. It automatically gets called whenever an object is created.
class MyClass:
def __init__(self, x):
self.x = x
my_object = MyClass(5)
print(my_object.x) # Output: 5__str__ returns a string representation of an object. Commonly it is used to provide a more human-readable output of an object.
class MyClass:
def __init__(self, x):
self.x = x
def __str__(self):
return f"MyClass with x = {self.x}"
my_object = MyClass(5)
print(my_object) # Output: MyClass with x = 5__len__ returns the length of an object.
class MyList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
my_list = MyList([1, 2, 3, 4, 5])
print(len(my_list)) # Output: 5__add__ is used to define the behavior of the + operator between two objects.
class MyNumber:
def __init__(self, x):
self.x = x
def __add__(self, other):
return MyNumber(self.x + other.x)
a = MyNumber(5)
b = MyNumber(10)
c = a + b
print(c.x) # Output: 15__eq__ is used to define the behavior of the == operator between two objects.
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
p1 = MyPoint(0, 0)
p2 = MyPoint(0, 0)
p3 = MyPoint(1, 1)
print(p1 == p2) # Output: True
print(p1 == p3) # Output: False__getitem__ is used to access the elements of an object using index notation.
class MyList:
def __init__(self, items):
self.items = items
def __getitem__(self, index):
return self.items[index]
my_list = MyList([1, 2, 3, 4, 5])
print(my_list[2]) # Output: 3__repr__ returns a string that represents the object in a way that can be used to recreate the object. Typically it is used for debugging.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person('{self.name}', {self.age})"
person = Person("Badal", 25)
print(repr(person)) # Output: "Person('Badal', 25)"






