Magic Methods
Magic Methods
Instrucror:
Done by Hafizullah Saadat
1
Introduction to Magic Methods
• Definition: Magic methods, also known as dander
methods (double underscore), are special methods in
Python that start and end with double underscores.
• Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Ali", 30) 5
The __str__ Method
• Purpose: Returns a human-readable string representation of
an object.
• Usage: Used by the print() function and str() function.
• Example:
def __str__(self):
return f"{self.name}, {self.age} years old"
print(p) # Output: Ali, 30 years old
6
The __repr__ Method
• Purpose: Returns a string that represents the object more
formally or unambiguously.
• Usage: Used by the repr() function and in debugging.
• Example:
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
print(repr(p)) # Output: Person(name=Ali, age=30)
7
The __len__ Method
• Purpose: Allows the use of the len() function on an object.
• Usage: Defines how the length of an object is calculated.
• Example:
def __len__(self):
return len(self.name)
print(len(p)) # Output: 5 (length of 'Ali')
8
The __getitem__ Method
• Purpose: Enables indexing and slicing of objects.
• Usage: Allows retrieval of items using square brackets.
• Example:
def __getitem__(self, index):
return self.name[index]
print(p[1]) # Output: l (second character in 'Ali')
9
The __setitem__ Method
• Purpose: Allows setting values using indexing.
• Usage: Enables modification of attributes through indexing.
• Example:
def __setitem__(self, index, value):
self.name = self.name[:index] + value + self.name[index + 1:]
p[1] = 'o'
print(p) # Output will change based on the implementation of
__str__ 10
The __delitem__ Method
• Purpose: Enables deletion of items using indexing.
• Usage: Allows removal of elements from an object.
• Example:
def __delitem__(self, index):
self.name = self.name[:index] + self.name[index + 1:]
del p[1]
print(p) # Output will change based on the implementation of __str__
11
The __add__ Method
• Purpose: Defines behavior for the addition operator (+).
• Usage: Customizes how two objects can be added together.
• Example:
def __add__(self, other):
return Person(self.name + other.name, self.age + other.age)
p2 = Person(" Bob", 25)
p3 = p + p2
print(p3) # Output will depend on the implementation of __str__
12
The __sub__ Method
• Purpose: Defines behavior for the subtraction operator (-).
• Usage: Customizes how two objects can be subtracted.
• Example:
def __sub__(self, other):
return self.age - other.age
age_difference = p - p2
print(age_difference) # Output will be based on ages
13
The __sub__ Method
• Example:
def __sub__(self, other):
return self.age - other.age
age_difference = p - p2
print(age_difference) # Output will be based on ages 14
Other Arithmetic Magic Methods
15
Enables iteration over an object.
• Usage: Allows use of a class in a loop (e.g., for loops).
• Example:
def __iter__(self):
self.index = 0
return self
def __next__(self):
16
Enables iteration over an object.
if self.index < len(self.name):
result = self.name[self.index]
self.index += 1
return result
raise StopIteration
for char in p:
print(char) # Outputs each character in 'Ali'
17
The __call__ Method
• Purpose: Allows an instance of a class to be called as a function.
• Usage: Customizes behavior when an object is called like a function.
• Example:
def __call__(self):
return f"{self.name} is called!"
print(p()) # Output: Alice is called!
18
The __contains__ Method
• Purpose: Defines behavior for the in operator.
• Usage: Customizes membership tests.
• Example:
def __contains__(self, item):
return item in self.name
print('A' in p) # Output: True (if 'A' is in 'Ali') 19
Use Cases for Magic Methods
21
Thanks
22