Why do operators and methods of built-in types differ

Discussion in 'Python' started by Csaba Hoch, Jan 31, 2009.

  1. Csaba Hoch

    Csaba Hoch Guest

    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
     
    Csaba Hoch, Jan 31, 2009
    #1
    1. Advertising

  2. Csaba Hoch

    andrew cooke Guest

    On Jan 31, 8:51 am, Csaba Hoch <> 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
     
    andrew cooke, Jan 31, 2009
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Latter
    Replies:
    10
    Views:
    887
    John Latter
    Sep 24, 2003
  2. Mr. SweatyFinger
    Replies:
    2
    Views:
    2,002
    Smokey Grindel
    Dec 2, 2006
  3. Alona
    Replies:
    2
    Views:
    653
  4. CC
    Replies:
    1
    Views:
    238
    Scott David Daniels
    Aug 20, 2007
  5. Pieter Van Waeyenberge

    offsetLeft & Top differ for different element types?

    Pieter Van Waeyenberge, Feb 15, 2004, in forum: Javascript
    Replies:
    0
    Views:
    118
    Pieter Van Waeyenberge
    Feb 15, 2004
Loading...

Share This Page