Python special methods.
2 min readJul 12, 2023
A set of predefined methods with double underscores (also known as dunder methods) that provide functionality to classes and objects in a special way.
Objects Special methods.
__init__(self, ...)
: The constructor method that is automatically called when an object is created. It initializes the object and sets its initial state.__str__(self)
: Returns a string representation of the object that is intended to be human-readable. It is called by thestr()
function or when an object is used in a print statement or formatted string.__repr__(self)
: Returns a string representation of the object that is mainly used for debugging and development purposes. It should ideally be a valid Python expression that could be evaluated to recreate the object. It is called by therepr()
function or when the object is displayed in the Python interactive interpreter.__len__(self)
: Returns the length of the object, allowing it to be used with thelen()
function.__getitem__(self, key)
: Allows objects to support indexing and enables accessing elements using square brackets, likeobj[key]
.__setitem__(self, key, value)
: Allows objects to support assignment to elements using square brackets, likeobj[key] = value
.__delitem__(self, key)
: Allows objects to support deletion of elements using thedel
statement and square brackets, likedel obj[key]
.__contains__(self, item)
: ReturnsTrue
orFalse
depending on whether the object contains the specified item. It enables the use of thein
andnot in
operators.__iter__(self)
: Returns an iterator object that allows iteration over the object's elements. It is used infor
loops and other iterable contexts.__next__(self)
: Returns the next item from an iterator object created by__iter__()
. It is used in conjunction with the__iter__()
method to implement iteration.__call__(self, ...)
: Allows objects to be called as if they were functions. It is invoked when the object is followed by parentheses, likeobj()
.