In Python, special methods (also known as magic methods or dunder methods) are identified by double underscores (e.g., __init__
, __str__
, __add__
). These methods allow you to define specific behaviors for your objects. Here's a list of some commonly used special methods:
__init__(self, ...)
: Constructor method, used to initialize object attributes.__del__(self)
: Destructor method, used to clean up resources when an object is deleted.__str__(self)
: String representation of an object when using str(obj)
or print(obj)
.__repr__(self)
: Developer-friendly representation of an object when using repr(obj)
.__len__(self)
: Defines the behavior when calling len(obj)
.__getitem__(self, key)
: Used to get an item using square brackets, e.g., obj[key]
.__setitem__(self, key, value)
: Used to set an item using square brackets, e.g., obj[key] = value
.__delitem__(self, key)
: Used to delete an item using del obj[key]
.__iter__(self)
: Returns an iterator object to support iteration over the object.__next__(self)
: Used in conjunction with __iter__
to define the next iteration element.__contains__(self, item)
: Checks if an item is present in the object using item in obj
.__call__(self, ...)
: Allows an object to be callable like a function, e.g., obj()
.__add__(self, other)
: Defines behavior for the addition operation +
.__sub__(self, other)
: Defines behavior for the subtraction operation ``.__mul__(self, other)
: Defines behavior for the multiplication operation ``.__truediv__(self, other)
: Defines behavior for the division operation /
.__floordiv__(self, other)
: Defines behavior for the floor division operation //
.__mod__(self, other)
: Defines behavior for the modulo operation %
.__pow__(self, other)
: Defines behavior for the power operation *
.