Properties - when and why

Matt Gerrans mgerrans at mindspring.com
Mon Jul 8 03:36:40 EDT 2002


> def V_homogenous(self):
>     V = self.V
>     return array((V.x,V.y,V.z,1.))
>
> Seriously, what COULD be simpler -- or, less special-case...?!

Exactly what I was thinking!   Alex, are you psychic, or was this obvious?
;-)

> > Is the when and why of using properties something that can be
> > explained in few enough words?
>
> Use properties when you want the syntax of attribute access
> and the semantics of a method call.  That has nothing to do
> with the fact that if you need "common subexpression elimination"
> you need to write that out explicitly -- Python never eliminates
> common subexpressions by itself.

Additionally, properties are of great value in creating read-only members
and are great for controlling a valid state of objects, since they can do
range-checking on the input.   Sure, you can do all this without properties
(as for instance, in Java, where the properties effect in JavaBeans is
achieved by an agreed-upon standard), but they make it much more clean and
standard.

Having been weaned (from MFC!) on Delphi and C++ Builder (and more recently
C#), I think properties are a great thing, especially for Python.   Since it
doesn't have strong typing, properties can go a long way in ensuring an
object's state remains valid or that an exception is raised close to the
actual cause of the problem (that being the bad assignment; without the
property, you might not discover the problem until much later, when the
member variable is used).   Properties also add flexibility: for instance,
with assignment, you could assign either a 3-item list or tuple to your W
property and it could be designed to work just fine either way.

Hmm, I hope that wasn't too many words.

- mfg





More information about the Python-list mailing list