Overriding a method at the instance level on a subclass of a builtin type
Bryan Olson
fakeaddress at nowhere.org
Tue Dec 2 21:44:27 EST 2008
Zac Burns wrote:
> 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.
One option is to re-assign the object's __class__, as in:
class XDict (dict):
pass
class ZDict (XDict):
def __getitem__(self, k):
whatever_you_want_to_do_once(self)
result = dict.__getitem__(self, k)
self.__class__ = XDict
return result
The first dict subtype is needed because __class__ assignment requires
that both the current and newly-assigned class be 'heap types', which
the native dict is not.
--
--Bryan
More information about the Python-list
mailing list