"Private" Member Variables

Steve Menard steve.menard at videotron.ca
Fri May 28 13:31:31 EDT 2004


Scott Brady Drummonds wrote:
> Hi, everyone,
> 
> I'm still learning Python as I develop a medium-sized project.  From my
> previous experience with C++, I've burnt into my mind the notion of
> information hiding.  I'm having trouble understanding to what extent I
> should follow this policy in my Python code so I thought I'd ask the group.
> 
> I read from a previous post that to attain a private-like status of member
> variables, I should prefix the variable name with two underscores ("__").
> This does work, but in another post someone asked me if this was really
> necessary.  Given that the very nature of the language precludes any
> compile-time type dependencies I'm wondering if there is any benefit to
> naming variables with leading underscores and providing accessor functions
> like this:
> 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?
> 
> 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?
> 
> Thanks,
> Scott
> 

I see no problem with exposing the attribute directly, if that attribute 
may be freely modified without verification. The main problem with doing 
this in C++ and other languages, is that changing to a calculated value 
down the road would break existing code.

In python, if an attribute suddenly needs to be validated at assignment 
time, of has to be calculated at "get" time, you can make it a property. 
Client code won;t see the difference.

However, for the sake of consistency, I would make all get/set accessed 
that cannot be direct into properties.

Steve



More information about the Python-list mailing list