"Private" Member Variables

Dave Brueck dave at pythonapocrypha.com
Fri May 28 13:35:50 EDT 2004


Scott wrote:
> 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.

Holy cow, Scott! Congratulations - many people come to Python from other
languages and are completely unable or unwilling to believe that Python's
approach to information hiding isn't broken. Many of them, upon seeing that it
is more relaxed than C++ even postulate that Python doesn't support
object-oriented programming (which is funny, but annoying).

I'm sure other people will better answer your question, but I just wanted to
say 'thanks' because it's refreshing to hear "This is different, what are some
good practices?" as opposed to "This is different, it must be broken!".

> 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?

IMO the thing that matters most is consistency. For a given class, just make
sure you go all one way or another - all direct access or all accessor
functions. I like the fact that you have the freedom to choose - some classes
are closer to C structures (they are mostly dumb data containers), so it makes
"sense" to access them in that way. Other classes more closely represent the
traditional notion of an object (data + operations on the data), so access
through functions is a cleaner interface and safeguards against fiddling with
class internals that could break things.

-Dave

P.S. The only time I use underscore prefixes is for the direct-access classes.
If I document the class as one in which you should use the accessors instead of
going direct, then I generally don't bother with the underscores.





More information about the Python-list mailing list