Bug overriding operators in new-style classes?
Nicodemus
nicodemus at globalite.com.br
Thu Jul 17 15:05:56 EDT 2003
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.
More information about the Python-list
mailing list