Objects with different data views

Paul Rubin http
Fri Oct 7 19:04:03 CEST 2005

Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> Anyone have any good ideas for how I should implement this?

These days you can use properties.  Before, you'd have had to do it
manually with __setattr__ / __getattr__ methods.  Here's how I'd do it
with properties, if I have the math right.  You're using a and b as
the canonical values of the variables, computing x and y from them,
and adjusting them when x and y change.

class Parrot(object):
  x = property(getx, setx)
  y = property(gety, sety)

  def getx(self):
     return self.a + self.b        
  def setx(self, x):
     y = self.y   # calls gety
     self.a, self.b = 2*x - y, y-x

  def gety(self):
     return self.a + 2*self.b
  def sety(self, y):
     x = self.x    # calls getx
     self.a, self.b = 2*x - y, y-x

More information about the Python-list mailing list