Newbie question about class operator overloading

Rory Campbell-Lange rory at campbell-lange.net
Wed Feb 16 17:13:54 EST 2005


Hi Steve

I've been playing around with your two suggestions. 

The Record class is an elegant solution. It doesn't however help in the
case where the class has the following general data structure (something
I should have stated originally):

    class.config1 = param
    class.config2 = param
    class.data    = {
                       'this' : []
                       'that' : []
                       ...
                    }

The __setitem__ and __getitem__ methods allow the class.data data
structure to be dealt with easily as self.data[key] = val
without worrying about getting involved with other variables such as
config1 and config2 (because potentially a data key could be called
'config1' for example.

So the __getitem__ and __setitem__ give data hiding properties when I
inherit from this class.

I think!
Anyway, I'm very grateful for your help.

Rory

On 15/02/05, Steven Bethard (steven.bethard at gmail.com) wrote:
> Rory Campbell-Lange wrote:

> >I am anxious about how best to set and access items one level down in a
> >data structure if I am using __setitem__ and __getitem__.
...

> >object['three'] = [0, 'val0'] # set
> >x =  object['three'][0]       # get
...

> py> data['one'].foo = 'val0'
> py> data
> {'two': Record(5, 6, {}, 8), 'one': Record('val0', 2, {}, 4)}
> py> data['one'].foo
> 'val0'
...
> ...     def __setitem__(self, x, value):
> ...         try:
> ...             name, index = x
> ...             self.data.setdefault(name, {})[index] = value
> ...         except ValueError:
> ...             self.data[x] = value

...
> py> c['one', 0] = 1

This does seem a lot more logical than my object['three'] = [0, 'val0'].
Thanks for this (and using try against a possible ValueError).

...
> As you can see, Python has builin syntax support to allow tuples to be 
> used as dict keys.  (The parentheses can be omitted.)
> 
> Still, I think the class-based solution is much better than the 
> __getitem__/__setitem__ one.
-- 
Rory Campbell-Lange 
<rory at campbell-lange.net>
<www.campbell-lange.net>



More information about the Python-list mailing list