Inheritance from builtin list and override of methods.

  • Thread starter Michalis Giannakidis
  • Start date
M

Michalis Giannakidis

Dear all

I tried to override methods of build in Python types, so as to change their
behavior.
I tried to override list.__getitem__ list.__setitem__ and some others alike
The test case is:

#!/usr/bin/env python
class L(list):
def __getitem__(self, i):
print 'G', i
return list.__getitem__(self, i)
def __setitem__(self, i, y):
print 'S:', i, y
return list.__setitem__(self, i, y)
def __setslice__(self, i, j, y):
print 'SL:', i, j, y
return list.__setslice__(self, i, j, y)
def __iter__(self, x):
print 'iter:', x
return list.__iter__(self, x)

l = L()
l.append(3) # this does not call my __setitem__
l.append(2)
l.append(1)
l[2] = 6 # this calls my __setitem__
l.sort(key=lambda x: x )
print l

I expected that the call to l.sort() would call my versions of the list
methods (iter, setitem etc ) but it didn't. Also the call to l.append didn't
call my setitem but the assignment l[2] = 6 did! I expected my versions of
iter, setitem, getitem to be called with the typical impementation of sorting
from C in mind.

Could someone please explain the reasoning/behabiour of these?

Python Version:
Python 2.4.2 (#1, May 26 2006, 14:35:35)
[GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2

Thank you very much in advance.

Michalis
 

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

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top