Special Methods in Python Explained.
We will try to understand these special methods via List Data Structure in Python. We can display the all the methods in List class by using dir(object) function. All the functions starting and ending with double underscore(__) forms a special methods in python.
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> lst1 = [1,2,3,4,5]
>>> lst2 = [6,7,8,9,10]
>>> lst1.__add__(lst2) #Calling a basic addition between 2 lists it will be same as lst1 + lst2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst1
[1, 2, 3, 4, 5]
>>> lst2
[6, 7, 8, 9, 10]
>>> lst1+lst2 # same as above operation
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst3 = lst1 + lst2
>>> lst3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
If we perform a basic operations like +,-,*, the corresponding special methods will be called if that particular datatype supports that operation.
>>> lst1.__class__
<type 'list'>
>>> lst1.__contains__(1)
True
>>> 1 in lst1 # In operator internally calls above __contains__ spec method
True
>>> lst1.__delitem__(1)
>>> lst1
[1, 3, 4, 5]
>>> del lst1[0] # calling shorthand del will internally calls __delitem__ as shown above.
>>> lst1
[3, 4, 5]
Operations attached to some of the special methods given here for reference.
'__delslice__', <==> del lst1[i:j]
'__doc__', ==> documentation string
'__eq__', <==> ==
'__format__', <==> .format()
'__ge__', <==> >=
'__getitem__', <==> lst1[i]
'__getslice__', <==> lst1[i:j]
'__gt__', <==> >
You can have operations shown below also.
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__setslice__',
'__sizeof__',
'__str_
For More Information
https://docs.python.org/2/reference/datamodel.html#special-method-names