0% found this document useful (0 votes)
9 views22 pages

Magic Methods

Uploaded by

hussainighadir8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views22 pages

Magic Methods

Uploaded by

hussainighadir8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

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.

• Purpose: They allow developers to define how objects of


a class behave with built-in functions and operators,
enabling operator overloading and custom object
behavior.
2
What are Magic Methods?
• Characteristics:
• Not called directly; they are invoked automatically by
Python.
• Provide a way to implement behavior for built-in
operations (e.g., addition, string representation).

• Examples: __init__, __str__, __add__, etc.


3
Common Magic Methods
Overview
List of common magic methods:
• __init__: Constructor method
• __str__: String representation
• __repr__: Official string representation
• __add__: Addition operator
• __len__: Length of an object
• __getitem__: Indexing
4
The __init__ Method
• Purpose: Initializes an object when it is created.
• Usage: Accepts parameters to set the initial state of the object.

• 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

• 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 14
Other Arithmetic Magic Methods

• Briefly list other arithmetic methods:


• __mul__(self, other): For multiplication (*).
• __truediv__(self, other): For division (/).
• __floordiv__(self, other): For floor division (//).
• __mod__(self, other): For modulus (%).

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

• Discuss practical scenarios where magic methods enhance


functionality:
• Custom collections (e.g., stacks, queues).
• Data handling classes (e.g., representing complex
numbers).
• Enabling intuitive operations between objects (e.g.,
mathematical operations).
20
Best Practices with Magic Methods

• Tips for using magic methods effectively:


• Use them to enhance readability and usability.
• Avoid overloading too many operators; it can make code
hard to understand.
• Clearly document the behavior of overloaded methods.

21
Thanks

22

You might also like