Python Magic Methods
Python Magic Methods
Madhuri Mahawar
• Example:
class Student:
def __init__(self,name):
[Link]=name
• __str__() is a magic method that returns a human-readable (informal) string
representation of an object.
• It is automatically called when the object is passed to the print() function or
converted to a string using str().
• Syntax:
def __str__(self):
return "String representation"
• Without __str__():
class Student:
def __init__(self,name):
[Link]=name
s=Student("Amit")
print(s)
class Student:
def __init__(self,name):
[Link]=name
def __str__(self):
return [Link]
s=Student("Amit")
print(s)
• Output: Amit
• __repr__() is a magic method that returns the official (developer-friendly) string
representation of an object.
• It is mainly used for debugging and development.
• Syntax:
def __repr__(self):
return "String representation"
class Student:
def __init__(self, name):
[Link] = name
def __repr__(self):
return f"Student('{[Link]}')"
s = Student("Amit")
print(repr(s))
• Output: Student('Amit')
• __getitem__() is a magic method that allows an object to support indexing ([]).
• It is automatically called whenever an object is accessed using square brackets.
• Syntax:
def __getitem__(self, key):
# Return the value corresponding to the key or index
class Sensor:
def __init__(self):
[Link] = [25.5, 27.2, 26.8, 28.1]
sensor = Sensor()
print(sensor[3])
• Output: 28.1
class Number:
def __init__(self,value):
[Link]=value
n1=Number(10)
n2=Number(20)
print(n1+n2)
class Number:
def __init__(self,value):
[Link]=value
def __add__(self,other):
return [Link]+[Link]
n1=Number(10)
n2=Number(20)
print(n1+n2)
Output: 30
• __eq__()
class Number:
def __init__(self,value):
[Link]=value
def __eq__(self,other):
return [Link]+[Link]
n1=Number(10)
n2=Number(20)
print(n1==n2)
Output: False
Thank You