Class.__class__ magic trick help

Oscar Benjamin oscar.benjamin at bristol.ac.uk
Tue Aug 21 10:14:43 EDT 2012


On 21 August 2012 14:50, Massimo Di Pierro <massimo.dipierro at gmail.com>wrote:

> Hello Oscar,
>
> thanks for your help but your proposal of adding:
>
> def __setitem__(self,key,value):
>    self.__dict__[key] = value
>    dict.__setitem__(self, key, value)
>
> does not help me.
>
> What I have today is a class that works like SlowStorage. I want to
> replace it with NewStorage because it is 10x faster. That is the only
> reason. NewStorage does everything I want and all the APIs work like
> SlowStorage except casting to dict.
>
> By defining __setitem__ as you propose, you solve the casting to dict
> issue but you have two unwanted effects: each key,value is store twice
> (in different places), accessing the elements becomes slower the
> SlowStprage which is my problem in the first place.
>
> The issue for me is understanding how the casting dict(obj) works and
> how to change its behavior so that is uses methods exposed by obj to
> do the casting, if all possible.
>

Then you have two options:
1) subclass object instead of dict - you're not using any of the features
of the dict superclass and the fact that it is a superclass is confusing
the dict() constructor.
2) use a different "cast" e.g. d = dict(a.items())

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120821/fe768b92/attachment.html>


More information about the Python-list mailing list