Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Why do operators and methods of built-in types differ

Reply
Thread Tools

Why do operators and methods of built-in types differ

 
 
Csaba Hoch
Guest
Posts: n/a
 
      01-31-2009
Hi,

if I write the following:

>>> 1+1

2

it seems to be exactly equivalent to this:

>>> (1).__add__(1)

2

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__([])

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
 
Reply With Quote
 
 
 
 
andrew cooke
Guest
Posts: n/a
 
      01-31-2009
On Jan 31, 8:51*am, Csaba Hoch <(E-Mail Removed)> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Why does digicam's max video rec time differ? DaveC Digital Photography 4 08-11-2012 10:22 AM
Is there a way to find the class methods of a class, just like'methods' finds the instance methods? Kenneth McDonald Ruby 5 09-26-2008 03:09 PM
findcontrol("PlaceHolderPrice") why why why why why why why why why why why Mr. SweatyFinger ASP .Net 2 12-02-2006 03:46 PM
offsetLeft & Top differ for different element types? Pieter Van Waeyenberge Javascript 0 02-15-2004 04:31 PM
Why do H1 sizes differ in IE6/Netscape7.1/Opera7.2 John Latter HTML 10 09-24-2003 06:54 AM



Advertisments