object indexing and item assignment

K

King

class MyFloat(object):
def __init__(self, value=0.):
self.value = value

def set(self, value):
self.value = value

def get(self):
return self.value

class MyColor(object):
def __init__(self, value=(0,0,0)):
self.value = (MyFloat(value[0]),
MyFloat(value[1]),
MyFloat(value[2]))

def set(self, value):
self.value[0].set(value[0])
self.value[1].set(value[1])
self.value[2].set(value[2])

def get(self):
return (self.value[0].get(),
self.value[1].get(),
self.value[2].get())

col = MyColor()
col[0].set(0.5) # 'MyColor' object does not support indexing
col[0] = 0.5 # 'MyColor' object does not support item assignment


The last two lines of the script produce errors. (written as
comments). I know it won't work as I am expecting. One solution I can
think of is to rewrite MyFloat and MyColor by sub classing default
python types "float and "tuple". Is this the only solution?

Prashant

Python 2.6.2
Win XP 32
 
B

Benjamin Kaplan

class MyFloat(object):
   def __init__(self, value=0.):
       self.value = value

   def set(self, value):
       self.value = value

   def get(self):
       return self.value

class MyColor(object):
   def __init__(self, value=(0,0,0)):
       self.value = (MyFloat(value[0]),
                       MyFloat(value[1]),
                       MyFloat(value[2]))

   def set(self, value):
       self.value[0].set(value[0])
       self.value[1].set(value[1])
       self.value[2].set(value[2])

   def get(self):
       return (self.value[0].get(),
               self.value[1].get(),
               self.value[2].get())

col = MyColor()
col[0].set(0.5) # 'MyColor' object does not support indexing
col[0] = 0.5 # 'MyColor' object does not support item assignment


The last two lines of the script produce errors. (written as
comments). I know it won't work as I am expecting. One solution I can
think of is to rewrite MyFloat and MyColor by sub classing default
python types "float and "tuple". Is this the only solution?

Prashant

Python 2.6.2
Win XP 32
--

In order to support indexing and item assignment, implement the
__getitem__ and __setitem__ methods.


def __getitem__(self, index) :
return self.value[index]

def __setitem__(self, index, value) :
self.value[index].set(value)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top