A question of variables

Stephan Houben 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
> class?

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
language.

A name beginning with two underscores gets "mangled", i.e.
the classname gets thrown in. This means that in the case:

class X:
    __foo = 1
    def print_x(self):
        print self.__foo

class Y(X):
    __foo = 2
    def print_y(self):
        print self.__foo

,when you do subsequently

>>> inst = Y()
>>> inst.print_x()
1
>>> inst.print_y()
2

,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.

Greetings,

Stephan




More information about the Python-list mailing list