1

Pointing the class method at the instance method is clearly causing problems:

class A(dict):          
    def __getitem__(self, name):
        return dict.__getitem__(self, name)

class B(object):
    def __init__(self):
        self.a = A()
        B.__getitem__ = self.a.__getitem__ 

b1 = B()
b1.a['a'] = 5
b2 = B()
b2.a['b'] = 10

c = b1['a']
d = b2['b']

Gives this error:

  File ... in __getitem__
    return dict.__getitem__(self, name)
KeyError: 'a'

What should I be doing here instead?

Dan
  • 33,953
  • 24
  • 61
  • 87
  • Are you trying to define a method function without using def? Why? What's wrong with def? – S.Lott Mar 26 '09 at 18:48
  • It's not dynamic? Let's presume that as well as __getitem__, I had another 20 methods - I would have to define each method again. (I'm not actually doing this, I'm just intrigued to know what the other ways of declaring functions are). – Dan Mar 27 '09 at 10:41

1 Answers1

7

__getitem__ only works in the class. You can't override it in a instance basis.

This works:

class A(dict):                  
    def __getitem__(self, name):
        return dict.__getitem__(self, name)

class B(object):
    def __init__(self):
        self.a = A()

    def __getitem__(self, item):
        return self.a[item]

b1 = B()
b1.a['a'] = 5
b2 = B()
b2.a['b'] = 10

c = b1['a']
d = b2['b']

If you want to define it in __init__ for some strange reason, you must create a descriptor:

def __init__(self):
    self.a = A()
    def mygetitem(self, item):
        return self.a[item]
    B.__getitem__ = types.MethodType(mygetitem, None, B)
nosklo
  • 217,122
  • 57
  • 293
  • 297