By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,818 Members | 1,262 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,818 IT Pros & Developers. It's quick & easy.

Inheritance from builtin list and override of methods.

P: n/a
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
Nov 26 '06 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.