[Tutor] Some help with classes

Michael P. Reilly arcege@shore.net
Tue, 28 Mar 2000 13:34:58 -0500 (EST)


> Hi all!
> I would like to know a way to encapusated a method that belows to a
> especific class.
> Something like it(ig in C++):
> class number
> {
>     private:
>         int n;
>     public:
>         void attribut (void)
>     ...(continue)
> }
> 
> My question is: How can I do something like 'private' in python? There a
> way?

You cannot get 'private' attributes (variables and methods) in Python,
but there are two conventions:

1) Attributes preceeded with a single underscore, eg. "_n", are to be
viewed as internal variables, not to be used externally.  In C++, these
are more like 'protected', since that name is still accessible to
subclasses.

  class Number:
    def __init__(self, value):
      self._n = value
    def __repr__(self):
      return '%s(%s)' % (self.__class__.__name, self._n)
    def add(self, value):
      self._n = self._n + value
  def IncrNum(Number):
    def incr(self):
      self._n = self._n + 1

2) Attributes starting with two underschores, eg. "__n" are renamed
when byte-compiled to "_CLASS__VARNAME".  Since the class's name is
used as part of the variable name, the variable "__n" in a subclass
would not be the same as in the superclass.  This is probably the
closest to 'private' as you will get.

  class Number:
    def __init__(self, value):
      self.__n = value
    def add(self, value):
      self.__n = self.__n + value
  def IncrNum(Number):
    def p_incr(self):
      self.__n = self.__n + 1
    def incr(self):
      self.add(1)

Calling IncrNum(3).p_incr() would raise an AttributeError accessing the
non-existant attribute "_IncrNum__n".  But calling "incr" would work
with both examples.  I could also still access IncrNum(3)._Number__n
with no errors (though this would be bad style).

Remember that nothing in Python is "private" (unless it is hidden
within a C extension type, but that's C :).

  -Arcege

References:
1.  Python Tutorial, 9.6 Private Variables,
    http://www.python.org/doc/current/tut/node11.html
2.  Python Reference Manual, 2.3.2 Reserved classes of identifiers,
    http://www.python.org/doc/current/ref/id-classes.html

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------