Why do operators and methods of built-in types differ
gagsl-py2 at yahoo.com.ar
Sat Jan 31 13:40:06 CET 2009
En Sat, 31 Jan 2009 09:51:35 -0200, Csaba Hoch <csaba.hoch at gmail.com>
> if I write the following:
> >>> 1+1
> it seems to be exactly equivalent to this:
> >>> (1).__add__(1)
> However, if I write invalid code and try to add a list to an int, the
> errors will be different:
> >>> 1+
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: unsupported operand type(s) for +: 'int' and 'list'
> >>> (1).__add__()
> I found that operator.__add__(1, ) gives the same result as 1+.
> What is the reason behind this difference between the __add__ operator
> and int.__add__?
The operator "+" does more than blindy calling left.__add__(right). In
this case, as int + list returns NotImplemented, it reverses the operands
and tries right.__radd__(left), and only then it gives up and raises
The actual rules are a bit more complex, involving type conversion too;
More information about the Python-list