Overriding a method at the instance level on a subclass of a builtin type

Arnaud Delobelle arnodel at googlemail.com
Wed Dec 3 14:11:47 EST 2008


"Zac Burns" <zac256 at gmail.com> writes:

> Sorry for the long subject.
>
> I'm trying to create a subclass dictionary that runs extra init code
> on the first __getitem__ call. However, the performance of __getitem__
> is quite important - so I'm trying in the subclassed __getitem__
> method to first run some code and then patch in the original dict
> method for the instance to avoid even the check to see if the init
> code has been run. Various recipes using instancemethod and the like
> have failed me.
>
> Curiously if __slots__ is not specified no error occurs when setting
> self.__getitem__ but the function is not overriden. If __slots__ is
> ['__getitem__'] however it complains that __getitem__ is read only. I
> do not understand that behavior.

You can change the class on the fly to achieve what you want:

>>> class D1(dict):
...     def __getitem__(self, key):
...         print 'first call'
...         self.__class__ = D2
...         return dict.__getitem__(self, key)
... 
>>> class D2(dict):
...     pass
... 
>>> d = D1(foo=42)
>>> d['foo']
first call
42
>>> d['foo']
42
>>> 

HTH

-- 
Arnaud



More information about the Python-list mailing list