views:

90

answers:

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?

+7  A: 

__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