Why do operators and methods of built-in types differ

andrew cooke andrew at acooke.org
Sat Jan 31 07:33:12 EST 2009


On Jan 31, 8:51 am, Csaba Hoch <csaba.h... at gmail.com> wrote:
> What is the reason behind this difference between the __add__ operator
> and int.__add__?

this is quite common in python.  the special methods like __add__ are
used to implement some functionality (like '+' in this case), but they
are not all of it.  for example, when
  a + b
is evaluated, a.__add__(b) is attempted, but if that fails (raises a
NotImplemented error) then b.__radd__(a) is tried instead.

so there's not a 1-to-1 correspondence between '+' and __add__() and
that is reflected in the exceptions, too.  when a method does not
exist a NotImplemented error is raised, but '+' contains extra logic
and raises a more useful error message.

does that make sense?  i should probably add that this is just how i
understand things - i assume it's correct, but i've not looked
anything up in the documentation.

andrew



More information about the Python-list mailing list