__getitem__ on new-style classes

simon at arrowtheory.com simon at arrowtheory.com
Thu Mar 10 22:12:10 EST 2005


What i'm trying to do is tie special methods of a "proxy" instance
to another instance:

def test1():
  class Container:
    def __init__( self, data ):
      self.data = data
      self.__getitem__ = self.data.__getitem__

  data = range(10)
  c = Container(data)
  print "test1"
  print c[3]

This works OK. But when I try the same thing on
new style classes:

def test2():
  print "test2"
  class Container(object):
    def __init__( self, data ):
      self.data = data
#      self.__dict__["__getitem__"] = self.data.__getitem__
      self.__setattr__( "__getitem__", self.data.__getitem__ )
  data = range(10)
  c = Container(data)
  print
  print c.__getitem__(3) # works OK
  print c[3] # fails

I get a "TypeError: unindexable object". It
seems that c[] does not call __getitem__ in this case.

The plot thickens, however, when one tries the following:

def test3():
  data = range(10)
  c = type( "Container", (), { "__getitem__":data.__getitem__ } )()
  print "test3"
  print c[3]

Which works fine. However, if I need to resort to
such trickery, no-one here where i work will have any idea
what it does :)

Would anyone like to shed some light on what is going on here ?

bye,

Simon.




More information about the Python-list mailing list