Lesson Plan
Dunder Methods
Lesson Plan
Polymorphism
Data and
Interpolation
EncapsulationIn
ML
Java + DSA
Dunder methods, also known as magic methods or special methods, in Python are special reserved methods
that are surrounded by double underscores (i.e., __method__). These methods allow you to define how
instances of your classes behave when they are used with built-in Python functions or operators. Understanding
dunder methods is crucial for creating custom objects that behave like built-in types or implementing operator
overloading in Python. Here's a detailed explanation of some commonly used dunder methods:
__init__(self, ...): This method is called when an instance of the class is initialized. It is used to initialize
instance variables and perform any setup required for the object.
__str__(self): This method is called when the str() function is used on an instance of the class. It should
return a string representation of the object.
Output:
__repr__(self): This method is called when the repr() function is used on an instance of the class. It
should return an unambiguous string representation of the object, which can be used to recreate the
object.
__add__(self, other): This method is called when the + operator is used with instances of the class. It
should return the result of addition.
Output:
__eq__(self, other): This method is called when the == operator is used with instances of the class. It
should return True if the objects are considered equal, False otherwise.
Output:
These are just a few examples of dunder methods in Python. There are many more dunder
methods available for various purposes, such as arithmetic operations, container behavior,
context management, and more.
THANK
YOU !