what about things like __*** ?

Eric Brunel eric.brunel at pragmadev.com
Tue Sep 3 09:51:58 CEST 2002


black wrote:
> Hi, all~
> 
> when reading the tutorial I met some trouble.(Maybe trifle to you all
> but really trouble to me)
> 
> That is I couldnt figure out what __*** is. Here is the description of
> that article but even confused me:
> 
> There is limited support for class-private identifiers. Any identifier
> of the form __spam (at least two leading underscores, at most one
> trailing underscore) is now textually replaced with _classname__spam,
> where classname is the current class name with leading underscore(s)
> stripped.
> 
> What's it trying to say please ???

As a good practice in object-oriented programming, the structure of a 
class, i.e. its actual attributes, are often hidden from the outside world. 
It's called "encapsulation". It helps to separate the interface of the 
class from the actual implementation of the methods, that shouldn't be 
known outside the class itself.

Languages like C++ or Java have a native support for encapsulation, by 
allowing to declare attributes "private" or "protected". A value of a 
private or protected attribute can't be read or set by another class than 
the owner class (or one of its sub-classes for protected attributes).

IIRC, before Python 2.0, there were no support at all for encapsulation in 
Python. So you could always do:

class C:
  def __init__(self):
    self.a = 12
o = C()
o.a = 13
print o.a

The attribute "a" of instances of class C can be read or modified outside 
the class, and there's no (simple...) means to prevent that.

>From Python 2.0, there's a (limited) support for encapsulation: if the name 
of an attribute begins with a double-underscore, it's just as if it had 
been declared private:

class C:
  def __init__(self):
    self.__a = 12
  def get_a(self):
    return self.__a
o = C()
o.__a = 13       # Does not work
print o.__a      # Again, does not work
print o.get_a()  # Works

class CC(C):
  def __init__(self):
    C.__init__(self)
    print self.__a    # Does *not* work

The attribute __a is private: it can be seen only in the class C. It's 
impossible to read or set it from outside the class, even in one of its 
sub-classes. This sounds like a big restriction, but is actually very often 
used in OO programming.

The actual mechanism involves a "name-mangling", and that's what the 
comment tried to explain. But it's not that important: the final result is 
just that any attribute beginning with a double-underscore is private.

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list