"Private" Member Variables

F. GEIGER fgeiger at datec.at
Sun May 30 11:53:39 EDT 2004


"Scott Brady Drummonds" <scott.b.drummonds.nospam at intel.com> schrieb im
Newsbeitrag news:c97r0b$jqq$1 at news01.intel.com...
> 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?

Classes should offer services, not data. This holds for any programming
language. If you remember this while designing your software you will stop
to think of variables and their not/privateness.

Most people who speak of information hiding don't get it right. They end up
def'ing private variables and then they write getters and setters to access
them. This is NOT information hiding, it's the opposite (simple data
containers being an exception, of course).

Now, if you know all this it really doen't matter much if you write
self.whatToSay or
self._whatToSay or
self.__whatToSay

because your call should be
myObj = MyClass("Hello")
myObj.sayIt(Printer())

and NOT
myObj = MyClass()
s = myObj._whatToSay
print s

In Python things concerning even the bad example are somewhat better because
you do not know explicitly what type s is of. In C++ most people show all
the world, that they access a string, no matter if they use a getter or not.
Sure, they def'ed the string as private, but the information is not hidden,
by no means: Everyone knows, it's a string!

HTH
Franz GEIGER

>
> 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
>
> --
> Remove .nospam from my e-mail address to mail me.
>
>
>





More information about the Python-list mailing list