overriding __getitem__ for a subclass of dict

Steve Howell showell30 at yahoo.com
Sun Nov 15 15:09:21 EST 2009


On Nov 15, 12:01 pm, Jon Clements <jon... at googlemail.com> wrote:
> On Nov 15, 7:23 pm, Steve Howell <showel... at yahoo.com> wrote:
>
> > I am more precisely looking for a way to change the behavior of foo
> > ['bar'] (side effects and possibly return value) where "foo" is an
> > instance of a class that subclasses "dict," and where "foo" is not
> > created by me.  The original post gives more context and example code
> > that does not work as I expect/desire.
>
> [quote fromhttp://docs.python.org/reference/datamodel.html]
> For instance, if a class defines a method named __getitem__(), and x
> is an instance of this class, then x[i] is roughly equivalent to
> x.__getitem__(i) for old-style classes and type(x).__getitem__(x, i)
> for new-style classes.
> [/quote]
>
> A quick hack could be:
>
> class Al(dict):
>   def __getitem__(self, key):
>     return self.spy(key)
>   def spy(self, key):
>     return 'Al'
>
> >>> a = Al()
> >>> a[3]
> 'Al'
> >>> a.spy = lambda key: 'test'
> >>> a[3]
> 'test'
> >>> b = Al()
> >>> b[3]
>
> 'Al'
>
> Seems to be what you're after anyway...
>

This is very close to what I want, but the problem is that external
code is defining Al, and I do not seem to be able to get this
statement to have any effect:

a.__getitem__ = lambda key: test

How can I change the behavior of a['foo'] without redefining Al?




More information about the Python-list mailing list