"Private" Member Variables

David Bolen db3l at fitlinxx.com
Fri May 28 19:37:23 EDT 2004


Marcus von Appen <mva at sysfault.org> writes:

> Yes. Imagine a class, which's attributes should only be able to hold a 
> specific value range, e.g. a triangle, of which the side length should not 
> exceed 10.
> If you would use the class as - let's say a third party developer and this
> class does not contain an accessor nor this 'private' indicator (_ or __),
> you possibly would not know about that limited value range.
> 
> You would simply type in triangle.side = 50.
> Now another calculation method using that triangle object could receive
> a value overflow, because it cannot calculate with such a 'big' value, but
> is limited to 10.
> 
> An accessor and private attribute could avoid this:
> * You would know, that the author of the class does not want you to modify
>   the attribute directly.
> * The accessor could test the value range at input.
> ...
> etc.pp.

Except that Python doesn't make you use accessors to gain this
behavior.  If in fact you have such a class, and yet you still want to
be able to permit users to use it in the above manner, simply make the
"side" attribute into a property (which function as accessors but
hidden behind normal attribute access syntax), and you get full
control when someone tries to assign something to do, at which point
you can validate the input all you want.

In terms of knowing that a class enforces such rules, that's something
I would expect documented by the class, regardless of implementation.

And the great thing is you can initially start out with a normal
non-property attribute, and convert it to a property at some point in
the future if you need to, without affecting any existing users of the
code (well, unless their prior use is later considered invalid, but
that would be true if you changed the rules checked by an accessor as
well).

-- David



More information about the Python-list mailing list