Sitemap

Python Magic Methods

2 min readFeb 16, 2023

--

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.

Press enter or click to view image in full size

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)"

--

--

Badal Panwar
Badal Panwar

Written by Badal Panwar

Python | Linux | PostgreSQL | Redis