"Private" Member Variables

Marcus von Appen mva at sysfault.org
Fri May 28 14:02:13 EDT 2004


"Scott Brady Drummonds" <scott.b.drummonds.nospam at intel.com> writes:

[...]
> class C:
>   ...
>   def value(self):
>     return self.__value
>   ...


> The problems that arise from directly relying on the member variable in C++
> (compile-time type dependency, as I said above) don't exist in Python.  So
> why provide an accessor at all?  Why not just allow direct reading and
> writing of the member variable?  Is there something here I'm missing?

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.

You see: It makes sense for other developers, so they can easily see the 
difference between your private attributes, which are not meant to be used 
directly and public usable ones.

Another advantage is that your private method and attribute documentations
are not shown using 'pydoc YourClass' ;-).

> What are your thoughts?  How much privacy should I build into my code?
> Should I be using variables beginning with "__" and accessors?  Or is that
> simply not necessary (or normal) in Python code?

As written above, it can make sense. You have to determine, if it is useful
for you :-).

Regards
Marcus

-- 
We don't understand the software, and sometimes we don't understand the 
hardware, but we can *see* the blinking lights!



More information about the Python-list mailing list