In Python, magic methods are special methods that start and end with double underscores, also known as dunder methods. These methods are used to provide functionality to objects that are not possible using regular methods.
Here are some commonly used magic methods in Python:
__init__(self, ...)
: This method is called when an object is created and initialized.__str__(self)
: This method is used to return a string representation of the object. It is called when thestr()
function is used on the object.__repr__(self)
: This method is used to return a string representation of the object. It is called when therepr()
function is used on the object.__len__(self)
: This method is used to return the length of the object. It is called when thelen()
function is used on the object.__getitem__(self, key)
: This method is used to get an item from an object using the square bracket notation.__setitem__(self, key, value)
: This method is used to set an item in an object using the square bracket notation.__delitem__(self, key)
: This method is used to delete an item from an object using the square bracket notation.__iter__(self)
: This method is used to return an iterator for the object. It is called when theiter()
function is used on the object.__next__(self)
: This method is used to return the next value in the iterator. It is called when thenext()
function is used on the iterator.__eq__(self, other)
: This method is used to check if two objects are equal. It is called when the==
operator is used on the objects.__lt__(self, other)
: This method is used to check if an object is less than another object. It is called when the<
operator is used on the objects.__add__(self, other)
: This method is used to add two objects together. It is called when the+
operator is used on the objects.__sub__(self, other)
: This method is used to subtract one object from another. It is called when the-
operator is used on the objects.__mul__(self, other)
: This method is used to multiply two objects together. It is called when the*
operator is used on the objects.__div__(self, other)
: This method is used to divide one object by another. It is called when the/
operator is used on the objects.