Inheritance from builtin list and override of methods.

Discussion in 'Python' started by Michalis Giannakidis, Nov 26, 2006.

  1. 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
     
    Michalis Giannakidis, Nov 26, 2006
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    0
    Views:
    337
  2. Michalis Giannakidis
    Replies:
    9
    Views:
    325
    Fredrik Lundh
    Nov 28, 2006
  3. DG
    Replies:
    3
    Views:
    346
    Terry Reedy
    Jul 22, 2009
  4. bdb112
    Replies:
    2
    Views:
    313
    Chris Torek
    Jul 2, 2011
  5. Ramza Brown
    Replies:
    1
    Views:
    125
Loading...

Share This Page