Bug overriding operators in new-style classes?

Discussion in 'Python' started by Nicodemus, Jul 17, 2003.

  1. Nicodemus

    Nicodemus Guest

    Hi all,

    I found a surprising behavior regarding new-style classes operator lookup.
    It seems that for operators, the instance methods are ignored. Observe:

    >>> class C:

    .... def foo(self):
    .... print 'foo'
    .... def __setitem__(self, k, v):
    .... print 'C.__setitem__', k, v
    ....
    >>> c = C()
    >>> c.foo()

    foo
    >>> c[1] = 1

    C.__setitem__ 1 1
    >>> def my_foo():

    .... print 'my_foo'
    ....
    >>> def my_setitem(k, v):

    .... print 'my_setitem', k, v
    ....
    >>> c.foo = my_foo
    >>> c.__setitem__ = my_setitem
    >>> c.foo()

    my_foo
    >>> c[1] = 1

    my_setitem 1 1
    >>>


    All is well. Now, if you use a new-style class, the instance method is not
    called:

    >>> class C(object):

    .... def foo(self):
    .... print 'foo'
    .... def __setitem__(self, k, v):
    .... print 'C.__setitem__', k, v
    ....
    >>> c = C()
    >>> c.foo()

    foo
    >>> c[1] = 1

    C.__setitem__ 1 1
    >>> def my_foo():

    .... print 'my_foo'
    ....
    >>> def my_setitem(k, v):

    .... print 'my_setitem', k, v
    ....
    >>> c.foo = my_foo
    >>> c.__setitem__ = my_setitem
    >>> c.foo()

    my_foo
    >>> c[1] = 1

    C.__setitem__ 1 1 # should print "my_setitem 1 1"
    >>>


    Is this a bug, or am I missing something? Any help would be appreciated.

    Regards,
    Nicodemus.
    Nicodemus, Jul 17, 2003
    #1
    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. David MacQuigg

    Bug in New Style Classes

    David MacQuigg, Jun 17, 2004, in forum: Python
    Replies:
    12
    Views:
    977
    David MacQuigg
    Jun 18, 2004
  2. Andrew Durdin

    Overriding logical operators?

    Andrew Durdin, Aug 21, 2004, in forum: Python
    Replies:
    3
    Views:
    408
    Michael Hudson
    Aug 23, 2004
  3. ankit
    Replies:
    1
    Views:
    328
    Alex Martelli
    Dec 22, 2005
  4. Isaac Rodriguez

    Are all classes new-style classes in 2.4+?

    Isaac Rodriguez, Dec 31, 2006, in forum: Python
    Replies:
    4
    Views:
    379
    Steven D'Aprano
    Dec 31, 2006
  5. Quek
    Replies:
    3
    Views:
    323
Loading...

Share This Page