Python's Special Methods
In Python, classes can define what are known as special methods. These methods are called "special" because they have a unique syntax and are used by the interpreter to perform certain built-in operations.
Syntax
Special methods are easily recognizable as their names start and end with double underscores ( _ ).
__specialmethod__
These are the same methods that the interpreter uses internally to process specific operations.
Some of these built-in special methods are particularly powerful and play a significant role in Python's object-oriented programming.
Note: Special methods in Python are also known as dunder methods, short for "double underscore."
Why Use Special Methods?
When you implement a special method in a class, it allows the class to emulate certain language operators.
This technique is known as operator overloading.
Example
Let's create a simple list with three elements:
>>> obj = ['a', 'b', 'c']
To access the third element in the list, you can simply type:
>>> obj[2]
'c'
You can achieve the same result using the special method __getitem__:
>>> obj.__getitem__(2)
'c'
This is, of course, a basic example, almost trivial. However, the power of operator overloading should not be underestimated.
In Python's object-oriented programming, mastering operator overloading opens up a world of possibilities.
List of Special Methods
Here is a list of common special methods:
- __init__: Initializes an instance of a class (constructor method)
- __str__: Converts an object to a string
- __del__: Destroys an instance of a class (destructor method)
- __eq__: Checks if two values are equal
- __gt__: Checks if one value is greater than another
- __ge__: Checks if one value is greater than or equal to another
- __lt__: Checks if one value is less than another
- __le__: Checks if one value is less than or equal to another
- __call__: Allows an instance to be called as a function
- __getitem__: Implements the bracket operator for item retrieval
- __setitem__: Implements the bracket operator for setting an item
- __delitem__: Deletes an item using the bracket operator
- __contains__: Checks if an item is in a container
- __add__: Adds two objects
- __sub__: Subtracts one object from another
- __mul__: Multiplies two objects
- __div__: Divides one object by another
- __mod__: Computes the remainder of a division
- __repr__: Provides a string representation of an object (used as a fallback if __str__ is not available)
- __new__
- __bytes__
- __format__
- __hash__
- __bool__
- __getattr__
- __getattribute__
- __setattr__
- __delattr__
- __dir__
- __get__
- __set__
- __delete__
- __set_name__
- __slots__
- __init_subclass__
- __instancecheck__
- __subclasscheck__
- __call__
- __length_hint__
- __missing__
- __iter__
- __reversed__
- __matmul__
- __truediv__
- __floordiv__
- __divmod__
- __pow__
- __lshift__
- __rshift__
- __and__
- __xor__
- __or__
- __radd__
- __rsub__
- __rmul__
- __rmatmul__
- __rtruediv__
- __rfloordiv__
- __rmod__
- __rdivmod__
- __rpow__
- __rlshift__
- __rrshift__
- __rand__
- __rxor__
- __ror__
- __iadd__
- __isub__
- __imul__
- __imatmul__
- __itruediv__
- __ifloordiv__
- __imod__
- __ipow__
- __ilshift__
- __irshift__
- __iand__
- __ixor__
- __ior__
- __neg__
- __pos__
- __abs__
- __invert__
- __complex__
- __int__
- __float__
- __round__
- __index__
- __enter__
- __exit__
- __await__
- __aiter__
- __anext__
- __aenter__
- __aexit__
How to View a Class's Special Methods
To see which special methods are associated with a class or object, simply use the help command with the class name in parentheses.
>>> help(classname)
This command will display a list of the class's methods, including any special methods.