Newbie question about class operator overloading

Rory Campbell-Lange rory at campbell-lange.net
Tue Feb 15 16:35:09 EST 2005


Anyone out there?

Criticism about the objective of my question, not just the execution,
gratefully received!

Basically, if I have a

    class This:
        def __init__(self, x, y):
            self.x=x
            self.y=y
            self.data = {}

and then make all my setitem and getitem calls refer to self.data; is it
sensible and right to be able to refer to self.data[n]?

Rory

On 15/02/05, Rory Campbell-Lange (rory at campbell-lange.net) wrote:
> Hi. I'm just starting to use python.
> 
> 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__.
> 
> At the moment I can do
> 
> for a data structure Data:
> 
>     object.Data = { 'one' : [1, 2, {}, 4],
>                     'two' : [5, 6, {}, 8]}
> 
> I can use normal __setitem__ and __getitem__ to address Data keys very
> easily
> 
> However, if I wish to access object.Data['one'][0] for instance, I am
> using the following:
> 
> object['three'] = [0, 'val0'] # set
> x =  object['three'][0]       # get
> 
> Is this advisable? I'm worried the syntax is very odd.
> 
> Extract from an example class:
> 
> 	def __setitem__ (self,key,value): 
> 		if type(value) == list and type(value[0]) == int:
> 			if key not in self.data:
> 				self.data[key] = {} 
> 			self.data[key][value[0]] = value[1]
> 		else:
> 			self.data[key] = value
> 
> 	def __getitem__ (self,key,value=None): 
> 		if not value==None:
> 			return self.data[key][value]
> 		else:
> 			return self.data[key]

-- 
Rory Campbell-Lange 
<rory at campbell-lange.net>
<www.campbell-lange.net>



More information about the Python-list mailing list