Specials Method
dunder" methods
In Python OOP, double underscore methods (also called "dunder" methods) are special methods that start and end with two underscores. These methods are used to define the behavior of the class for various operations such as comparison, mathematical operations, and string representation.
Here are some commonly used double underscore methods in Python OOP:
__init__(self, ...)
: This method is called when an object is created from the class and is used to initialize the object's attributes.__str__(self)
: This method is called when the object is converted to a string using thestr()
function or when it is printed using theprint()
function. It returns a string representation of the object.__eq__(self, other)
: This method is called when two objects are compared using the==
operator. It returnsTrue
if the two objects are equal, andFalse
otherwise.__lt__(self, other)
: This method is called when two objects are compared using the<
operator. It returnsTrue
if the first object is less than the second object, andFalse
otherwise.__add__(self, other)
: This method is called when two objects are added using the+
operator. It returns a new object that is the result of the addition.
There are many other double underscore methods that can be used to define the behavior of a class. They are all prefixed and suffixed with double underscores, which makes them easy to identify.
In summary, double underscore methods are special methods in Python OOP that are used to define the behavior of a class for various operations. They all start and end with two underscores, which makes them easy to identify.
Last updated