Fundamentally, there is no difference. One is a method called __add__
and the other is a method called add
.
However, this is a convention which the Python interpreter, and various libraries, use to designate methods that are somehow "special". They are called magic methods. For example, a + b
is essentially syntactic sugar for a.__add__(b)
. Really:
>>> (1).__add__(2)
3
This means if you create a class for which you want addition to be meaningful, instead of calling your method, say, addTo
and then doing foo.addTo(bar)
, you can call the method __add__
and do foo + bar
instead.
Other magic methods: a - b
is equivalent to a.__sub__(b)
, len(a)
is equivalent to a.__len__()
, cmp(a, b)
is equivalent to a.__cmp__(b)
. a = MyClass()
causes the new object's __init__
method to be called. And many more.