Mailing List Archive

A question of variables
"Carlos Ors" <cors@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
A question of variables [ In reply to ]
Carlos Ors wrote:
>
> How can I declare a variable as a private variable inside a method of a
> class?

All variables defined inside a method of a class are private to
that method except ones declared global with the global statement.
The same applies to functions.

"Private" instance attributes can be created using the __XXX
convention, e.g. self.__privatevar = 1. These are only
useable for methods defined in the same class, not for methods
defined in subclasses.

--
Marc-Andre Lemburg
______________________________________________________________________
Y2000: 133 days left
Business: http://www.lemburg.com/
Python Pages: http://www.lemburg.com/python/