Inheritance from builtin list and override of methods.

Michalis Giannakidis mgiann at beta-cae.gr
Sun Nov 26 17:04:54 CET 2006


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

-- 
Michalis Giannakidis



More information about the Python-list mailing list