properties setting each other

Diez B. Roggisch deets at nospam.web.de
Wed Sep 3 10:42:11 EDT 2008


mk schrieb:
> Hello everyone,
> 
> I try to set two properties, "value" and "square" in the following code, 
> and arrange it in such way that setting one property also sets another 
> one and vice versa. But the code seems to get Python into infinite loop:
> 
>  >>> import math
>  >>> class Squared2(object):
> 
>     def __init__(self, val):
>         self._internalval=val
>         self.square=pow(self._internalval,2)
>        
>     def fgetvalue(self):
>         return self._internalval
>        
>     def fsetvalue(self, val):
>         self._internalval=val
>         self.square=pow(self._internalval,2)
>        
>     value = property(fgetvalue, fsetvalue)
> 
>     def fgetsquare(self):
>         return self.square
>     def fsetsquare(self,s):
>         self.square = s
>         self.value = math.sqrt(self.square)
>        
>     square = property(fgetsquare, fsetsquare)
> 
>     
>  >>> a=Squared2(5)
> 
> Traceback (most recent call last):
>   File "<pyshell#11>", line 1, in <module>
>     a=Squared2(5)
>   File "<pyshell#10>", line 5, in __init__
>     self.square=pow(self._internalval,2)
>   File "<pyshell#10>", line 19, in fsetsquare
>     self.square = s
>   File "<pyshell#10>", line 19, in fsetsquare
>     self.square = s
>   File "<pyshell#10>", line 19, in fsetsquare
>     self.square = s
>   File "<pyshell#10>", line 19, in fsetsquare
>     self.square = s
>   File "<pyshell#10>", line 19, in fsetsquare
>     self.square = s
>   File "<pyshell#10>", line 19, in fsetsquare
> 
> ...
> 
> Is there a way to achieve this goal of two mutually setting properties?
> 

Better to make the getter for square return the square of value, and the 
setter of square compute the root & set that. Like this:

class Squared2(object):

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


     @apply
     def squared():
         def fset(self, squared):
             self.value = math.sqrt(squared)

         def fget(self):
             return self.value ** 2

         return property(**locals())

Diez



More information about the Python-list mailing list