properties setting each other

Wojtek Walczak gminick at bzt.bzt
Wed Sep 3 10:31:17 EDT 2008


On Wed, 03 Sep 2008 15:57:50 +0200, mk wrote:

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

> Is there a way to achieve this goal of two mutually setting properties?

My attempt:
---
import math

class Square(object):
   def __init__(self, val):
      self._square = pow(val, 2)
      self._value = math.sqrt(self.square)

   def getsquare(self):
      return self._square

   def setsquare(self, square):
      self._square = square
      self._value = math.sqrt(self._square)

   square = property(getsquare, setsquare)

   def getvalue(self):
      return self._value

   def setvalue(self, value):
      self._value = value
      self._square = math.pow(value, 2)

   value = property(getvalue, setvalue)


a = Square(5)
print a.square
print a.value
a.value = 10
print a.square
print a.value
a.square = 64
print a.square
print a.value
---

and the result:

$ python sqval.py
25
5.0
100.0
10
64
8.0
$ 

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/



More information about the Python-list mailing list