Inheritance from builtin list and override of methods.

Michalis Giannakidis mgiann at beta-cae.gr
Mon Nov 27 10:33:48 CET 2006


> in general, methods on C objects are implemented in terms of operations
> on the internal data structures, not in terms of a subset of the methods
> already provided by the object.

But what is the reason that the assignment 
l[2] = 6 
call my function, but
l.append(3) 
doesn't ?

Also, why can't I override these functions (for example in order to get access 
to the list.sort() internals)? Or can I?


#!/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

-- 
Michalis Giannakidis



More information about the Python-list mailing list