[Tutor] dynamic property of a class ?

Magnus Lyckå magnus@thinkware.se
Fri Jul 11 21:26:59 2003


At 18:37 2003-07-11 -0500, pan@uchicago.edu wrote:
>I'm wondering if it's possible to make a class with dynamic
>properties. For example, a normal class:
>
>class car(object):
>
>       def set_doors(self, val):
>             self.__dict__['__doors']= val
>
>       def get_doors(self):
>             return self.__dict__['__doors']
>
>       doors= property(get_doors, set_doors)
>
>c = car()
>c.doors = 4
>print c.doors
>
>So far so good.
>
>Now, is it possible to make this:
>
>c.color= 'black'
>print c.color
>
>and make 'color' a property (instead of an entry in the self.__dict__)
>at the runtime, even though it is not defined in the class ?

It's certainly easy to add the feature to the class dynamically:

 >>> class car(object):
...     def set_doors(self, val):
...             self.__dict__['__doors']= val
...     def get_doors(self):
...             return self.__dict__['__doors']
...     doors= property(get_doors, set_doors)
...
 >>> c = car()
 >>> c.doors = 4
 >>> print c.doors
4
 >>> def set_color(self, color):
...     if color in ['blue', 'red', 'green']:
...             self.__color = color
...     else:
...             self.__color = 'black'
...
 >>> def get_color(self):
...     return self.__color
...
 >>> car.color = property(get_color, set_color)
 >>> c.color = '42'
 >>> print c.color
black

but doing "c.color ..." instead of "car.color" won't work. I.e. you
can affect all instances of a class in runtime. But if you want
instances to behave differently, they should really have different
classes. It's more or less the definition of classes that two
instances of the same class share the same behaviour...


--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language