properties setting each other

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Sep 3 13:38:13 EDT 2008


Maric Michaud a écrit :
> Le Wednesday 03 September 2008 17:40:43 mk, vous avez écrit :
>>> Note that if one property can really be computed from another, this kind
>>> of thing could be considered as bad design (except if the computation is
>>> heavy).
>> Hmm, why? Is the line of thinking smth like: because the variables
>> should be kept to minimum and they should be calculated at the moment
>> they are needed?
> 
> Because you have to make extra effort to keep the logical relation between 
> value and square. self._square is not really needed, and what is not needed 
> is just extra hassle.
> 
> Doesn't it clear that your code is more hard to maintain than the 
> alternative :
> 
> class Squared(object):
> 
>         def __init__(self, val):
>                 self._val=val
>                 
>         def fgetvalue(self):
>                 return self._val
>         def fsetvalue(self, val):
>                 self._val=val
>         value = property(fgetvalue, fsetvalue)
> 
>         def fgetsquare(self):
>                 return self.value ** 2
>         def fsetsquare(self,s):
>                 self.value = math.sqrt(s)
>         square = property(fgetsquare, fsetsquare)

FWIW, if there's no computation on getting or setting value, you can 
make it a plain attribute.

But while it's quite clear that in this example use case it would be 
better  to have only one property (weither square or value, depending on 
which is the most often use), things are not always that simple in real 
world code, and - as you mentionned - there may be times where you have 
interdependant properties and really want to avoid recomputing the same 
thing over and over. Now there's no one size fits all solution here - 
it's an optimization problem, and as such depends on real use cases.






More information about the Python-list mailing list