Newbie question about class operator overloading

Steven Bethard steven.bethard at gmail.com
Wed Feb 16 17:26:43 EST 2005


Rory Campbell-Lange wrote:
> 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.

Yeah, if the keys of your data dict might collide with the attributes in 
your object, you can't make _data_ a Record type.  On the other hand, 
you can make the items _within_ data Record types, which is what my 
original suggestion said.  For example:

py> class Record(object):
...     def __init__(self, foo, bar, dict, baz):
...         self.foo = foo
...         self.bar = bar
...         self.dict = dict
...         self.baz = baz
...     def __repr__(self):
...         return 'Record(%r, %r, %r, %r)' % (
...             self.foo, self.bar, self.dict, self.baz)
...
py> class C(object):
...     def __init__(self, config1, config2):
...         self.config1 = config1
...         self.config2 = config2
...         self.data = dict(this=Record(1, 2, {}, 4),
...                          that=Record(5, 6, {}, 8))
...     def __getitem__(self, item):
...         return self.data[item]
...
py> c = C(True, False)
py> c['this']
Record(1, 2, {}, 4)
py> c['that']
Record(5, 6, {}, 8)
py> c['this'].foo
1
py> c['that'].bar
6
py> c['that'].baz = 42
py> c['that']
Record(5, 6, {}, 42)

>>...     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).

No prob.  Especially if you expect mostly to get items of the form 
(name, index), the try/except is the way to go.

STeVe



More information about the Python-list mailing list