0% found this document useful (0 votes)
6 views15 pages

Python Magic Methods

The document explains magic methods in Python, which are special methods that allow customization of object behavior for built-in operations. It provides examples of various magic methods such as __init__(), __str__(), __repr__(), __getitem__(), __add__(), and __eq__(), demonstrating their usage and output. These methods enable operator overloading and make user-defined classes behave like built-in objects.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

Python Magic Methods

The document explains magic methods in Python, which are special methods that allow customization of object behavior for built-in operations. It provides examples of various magic methods such as __init__(), __str__(), __repr__(), __getitem__(), __add__(), and __eq__(), demonstrating their usage and output. These methods enable operator overloading and make user-defined classes behave like built-in objects.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dr.

Madhuri Mahawar

Department of Mechatonics Engineering

Sanjivani College of Engineering, Kopargaon


• Also called special methods or dunder methods.
• Predefined methods in Python that begin and end with double underscores (__).
• Allow programmers to define or customize the behavior of objects for built-in
operations such as object creation, printing, comparison, arithmetic operations,
and length calculation.
• Automatically invoked by Python
• Define object behavior
• Enable operator overloading
• Make user-defined classes behave like built-in objects
Magic Method Purpose
__init__() Initializes the object
__str__() Returns a readable string
__eq__() Compares two objects
__add__() Adds two objects
__sub__() Subtracts two objects
__len__() Returns the length
__lt__() Less than comparison
__gt__() Greater than comparison
__repr__() Official string representation
__getitem__() Indexing using obj[key]
• Called automatically during object creation.

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

• Output: <__main__.Student object at 0x...>


• With __str__():

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]

def __getitem__(self, index):


return [Link][index]

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)

Output: TypeError: unsupported operand type(s) for +: 'Number' and 'Number'


• __add__()

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

You might also like