Properties - when and why

Arthur Siegel ajs at ix.netcom.com
Sun Jul 7 19:48:11 EDT 2002


Learning something about properties - as usual the hard way.
Beginning to conclude that they, as I recently learned with __slots__,
are more "special case" than I first understood.

Say self.W and self.U are each 3 element vectors referenced on
initialization, with attributes x,y, z. V is a calculated vector.  V=W-U

def get_V(self):
   return self.W-self.U

V=properties(get_V)

But occasionally I need to access V's attributes individually.

def V_homogenous(self):
    return array((V.x,V.y,V.z,1.))

Have I not just made three calls to the vector subtraction
of the get_V method? Not good.

Could have done:
def get_V(self):
   self._V  = self.W - self.V
   return self._V

def V_homogenous(self):
    return array((self._V.x,self._V.y,self._V.z,1.))

But now the use of the properties facility seems superfluous and
redundant. As a practical matter its self._V, the old style attribute
I will be referencing, not self.V, the new style property.

Is the when and why of using properties something that can be
explained in few enough words?

Art







More information about the Python-list mailing list