object indexing and item assignment

John Posner jjposner at optimum.net
Fri Nov 13 13:21:30 EST 2009


King wrote:

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

King, I think you might be trying too hard. (Since I don't know your 
"big picture", my suspicion might be wrong.) Python does not *require* 
you to implement "get" and "set" methods in user-defined classes. More 
detail ...

* You might not need the MyFloat class at all. Try using a plain old 
Python "float" value.

* You don't need the "set" and "get" methods in the MyColor class. So 
this might suffice:

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

It's important for self.value to be a *list* object only if you want 
modify individual components of a MyColor instance.  If you *do* want to 
modify individual components, then it *does* make sense to implement 
"set" and "get" methods:

        def set_comp(self, index, comp_value):
            self.value[index] = comp_value

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

For debugging, it makes senses to implement a __str__ or __repr__ 
method, so that "print" produces useful output:

        def __str__(self):
            return "MyColor: %3.1f %3.1f %3.1f" % tuple(self.value)

Putting it all together ...

#-----------------
class MyColor(object):
    def __init__(self, value=(0.,0.,0.)):
        self.value = list(value)

    def __str__(self):
        return "MyColor: %3.1f %3.1f %3.1f" % tuple(self.value)

    def set_comp(self, index, comp_value):
        self.value[index] = comp_value

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

col = MyColor()
print col              # output: MyColor: 0.0 0.0 0.0

col.set_comp(0, 0.5)
print col              # MyColor: 0.5 0.0 0.0

col.set_comp(2, 0.7)
print col              # MyColor: 0.5 0.0 0.7

col = MyColor((0.2, 0.3, 0.4))
print col              # MyColor: 0.2 0.3 0.4
#-----------------

-John




More information about the Python-list mailing list