[Poll] Private variables

Ken Seehof kseehof at neuralintegrator.com
Wed Sep 12 21:27:48 CEST 2001


Actually a member is private if it starts with 2 underscores and does not
end with 2 underscores.  There is no special meaning for a single
terminating underscore.

By convention, starting and ending with double underscore is reserved for
special functions such as __init__ and __add__ (which are not private).

>>> class X:
...  def __init__(self):
...   self.__priv = 'spammity'
...
>>> x = X()
>>> x.__priv
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: X instance has no attribute '__priv'
>>> x._X__priv
'spammity'

I rarely use private members, and tend to use the single underscore
convention to say that a member is intended to be private.  You could say I
don't really mind giving my users enough rope to shoot themselves in the
foot. :-)

I use true private members when I feel like being extra careful, or when I
want to avoid base class / derived class namespace clashes.

There are some silly people who would claim that python doesn't have private
members at all (and therefore is not object oriented) because the so called
private members are accessible by the _class__attr notation.  All I can say
to such people is "you are silly".  Anyway I can be silly too: it turns out
that C++ is not object oriented either because you can include the
following:

#define private public

I've also heard a particularly bizzare counterargument.  Apparently it is
possible for private to change the relative addresses of member data, so the
above hack is totally unsafe, therefore C++ is object oriented after all.
Huh?

----- Original Message -----
From: "Alexandre Fayolle" <alf at orion.logilab.fr>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Wednesday, September 12, 2001 2:16 AM
Subject: [Poll] Private variables


> It is possible in python to get private class members by using names
> beginning with 2 underscores, and finished by at least 1 underscore.
>
> I personnally tend to use class member names beginning with one
> underscore to indicate that the member is 'internal' and should not
> be called by external applications, and from looking at the standard
> library source code, it seems that this is more common than the official
> way mentionned hereabove.
>
> I would like to hear what the opinion of pythoneers is on that topic.
>
> Please feel free to point me to the list archives if this has already
> debated over and over.
>
> Alexandre Fayolle
> --
> LOGILAB, Paris (France).
> http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org
> Narval, the first software agent available as free software (GPL).
> --
> http://mail.python.org/mailman/listinfo/python-list






More information about the Python-list mailing list