A question of variables
stephan at pcrm.win.tue.nl
Fri Aug 20 09:38:08 CEST 1999
"Carlos Ors" <cors at recercai.com> writes:
> How can I declare a variable as a private variable inside a method of a
Variables in a method are always private.
In a class, you can use names with begin with one underscore,
e.g. _foo, or with two underscores, e.g. __foo.
A name beginning with one underscore is a polite suggestion to
whoever is going to use the class in the future not to stomp
on this name. However, there is no intrinsic protection from the
A name beginning with two underscores gets "mangled", i.e.
the classname gets thrown in. This means that in the case:
__foo = 1
__foo = 2
,when you do subsequently
>>> inst = Y()
,which shows that the __foo in class X and the __foo in class Y
are actual replaced by different names, namely _X__foo and _Y__foo.
However, the variables can still be accessed by anyone using
these mangled names!
The bottom line is that access protection in Python can always
be circumvented. However, doing so is of course a Bad Idea.
More information about the Python-list