Why do operators and methods of built-in types differ

C

Csaba Hoch

Hi,

if I write the following:
2

it seems to be exactly equivalent to this:
2

However, if I write invalid code and try to add a list to an int, the
errors will be different:
Traceback (most recent call last):
NotImplemented

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__?

Thank you,
Csaba
 
A

andrew cooke

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top