Learning Sections show
Magic/Dunder Methods in Python
Magic methods, also known as dunder (double underscore) methods, in Python are special methods that begin and end with double underscores. They allow the customization of the behavior of built-in Python operations for user-defined classes.
Common Magic Methods
1. __init__
Initializes a new instance of a class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(person.name) # Output: Alice
print(person.age) # Output: 30
2. __str__
Returns a string representation of the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
person = Person("Alice", 30)
print(person) # Output: Person(name=Alice, age=30)
3. __repr__
Returns an unambiguous string representation of the object, often one that could be used to recreate the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
person = Person("Alice", 30)
print(repr(person)) # Output: Person(name='Alice', age=30)
4. __add__
Defines the behavior of the addition operator +
for the objects of the class.
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)
v1 = Vector(2, 3)
v2 = Vector(4, 5)
result = v1 + v2
print(result.x, result.y) # Output: 6 8
5. __len__
Defines the behavior of the len()
function for the objects of the class.
class MyList:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
my_list = MyList([1, 2, 3])
print(len(my_list)) # Output: 3
Other Dunder Methods
__getitem__
,__setitem__
,__delitem__
: Indexing operations__iter__
,__next__
: Iterator protocol__call__
: Callable objects__eq__
Defines the functionality of the equality operator